package com.ikangtai.shecare.main;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.Constant;
import com.ikangtai.shecare.common.EnConstant;
import com.ikangtai.shecare.common.RecordFragmentCommonList;
import com.ikangtai.shecare.common.al.Algorithm;
import com.ikangtai.shecare.common.al.CycleUnitDS;
import com.ikangtai.shecare.common.al.DayUnitDSInput;
import com.ikangtai.shecare.common.al.DayUnitDSOutput;
import com.ikangtai.shecare.common.al.UserUnitDS;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.baseView.pickerDialog.recordPickerDialog.BrandPickerDialog;
import com.ikangtai.shecare.common.baseView.pickerDialog.recordPickerDialog.DateTimePickerDialog;
import com.ikangtai.shecare.common.baseView.pickerDialog.recordPickerDialog.TemperaturePickerDialog;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordOptionCopulationButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordOptionMensesButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordOptionSymptomButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectBBTContentButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectBUltraButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectCopulationButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectCopulationContentButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectEarlyPregnancyButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectMensesButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectMucusButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectOvulationButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectOvulationContentButton;
import com.ikangtai.shecare.common.baseView.verticalViewPager.VerticalAdapter;
import com.ikangtai.shecare.common.baseView.verticalViewPager.VerticalViewPager;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.db.sync.SyncALData;
import com.ikangtai.shecare.common.db.sync.SyncRecordInfo;
import com.ikangtai.shecare.common.eventBusMsg.AlgoUpdateMsg;
import com.ikangtai.shecare.common.eventBusMsg.CurveMsg;
import com.ikangtai.shecare.common.eventBusMsg.RecordChange;
import com.ikangtai.shecare.common.eventBusMsg.RecordInfo;
import com.ikangtai.shecare.common.eventBusMsg.TemperUploadMsg;
import com.ikangtai.shecare.common.eventBusMsg.ViewPagerNumMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncALDataMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncRecordInfoMsg;
import com.ikangtai.shecare.common.swipemenulistview.SwipeMenuListView;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.InternetUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.common.util.SelfPermissionUtil;
import com.ikangtai.shecare.common.util.TasksUtil;
import com.ikangtai.shecare.home.calendar.CalendarActivity;
import com.ikangtai.shecare.personal.TestPaperHelpActivity;
import com.ikangtai.shecare.record.CameraActivity;
import com.ikangtai.shecare.record.EarlyPregnancyPaperPhotoAdapter;
import com.ikangtai.shecare.record.HCGCameraActivity;
import com.ikangtai.shecare.record.OvuPaperPhotoAdapter;
import com.ikangtai.shecare.record.bean.UserRecordData;
import com.ikangtai.shecare.record.bean.UserTemperatureInfo;
import com.jaeger.library.StatusBarUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

/**
 * A simple {@link Fragment} subclass.
 */
public class RecordFragment extends Fragment {

    private TextView bbtText, bbtTimeText, otherTemperature1Text, otherTemperature1TimeText;
    private TextView otherTemperature2Text, otherTemperature2TimeText, otherTemperature3Text, otherTemperature3TimeText;
    private RecordSelectButton recordTemperatureRecordBtn;
    private RecordSelectButton recordTemperatureTimeBtn;
    private Button recordTemperatureConfirmAddBtn;
    private View viewFragment;
    private TopBar topBar;
    private Button record_bbt_base_temperature_edit_btn, record_bbt_other_temperature1_edit_btn, record_bbt_other_temperature2_edit_btn, record_bbt_other_temperature3_edit_btn;
    private Button record_bbt_base_temperature_delete_btn, record_bbt_other_temperature1_delete_btn, record_bbt_other_temperature2_delete_btn, record_bbt_other_temperature3_delete_btn;
    private Button record_bbt_other_temperature1_changebbt_btn, record_bbt_other_temperature2_changebbt_btn, record_bbt_other_temperature3_changebbt_btn;
    //private OptimizedFragmentTabHost optimizedFragmentTabHost;
    RelativeLayout record_temperature_edit_layout;
    LinearLayout record_temperature_base_temperature_layout;
    LinearLayout record_temperature_base_temperature_edit_layout;
    LinearLayout record_temperature_other_temperature1_layout;
    LinearLayout record_temperature_other_temperature1_edit_layout;
    LinearLayout record_temperature_other_temperature2_layout;
    LinearLayout record_temperature_other_temperature2_edit_layout;
    LinearLayout record_temperature_other_temperature3_layout;
    LinearLayout record_temperature_other_temperature3_edit_layout;
    View record_bbt_layout;
    View record_mucus_layout;
    View record_left_content_layout;

    private RadioGroup recordRightMarksGroup;

    //record_mucus view
    RecordSelectMucusButton recordMucusStatusDryButton;
    RecordSelectMucusButton recordMucusStatusWetButton;
    RecordSelectMucusButton recordMucusStatusMilkButton;
    RecordSelectMucusButton recordMucusStatusWateryButton;
    RecordSelectMucusButton recordMucusFlowNoButton;
    RecordSelectMucusButton recordMucusFlowLessButton;
    RecordSelectMucusButton recordMucusFlowAverageButton;
    RecordSelectMucusButton recordMucusFlowManyButton;
    RecordSelectMucusButton recordMucusColorTransparentButton;
    RecordSelectMucusButton recordMucusColorWhiteButton;
    RecordSelectMucusButton recordMucusColorBloodButton;
    RelativeLayout record_mucus_edit_layout;

    RecordSelectMensesButton recordMensesYesBtn;
    RecordSelectMensesButton recordMensesNoBtn;
    RecordSelectMensesButton recordMensesDysmenorrheaNoBtn;
    RecordSelectMensesButton recordMensesDysmenorrheaLessBtn;
    RecordSelectMensesButton recordMensesDysmenorrheaMiddleBtn;
    RecordSelectMensesButton recordMensesDysmenorrheaSeroiusBtn;
    RecordSelectMensesButton recordMensesFlowBtn1;
    RecordSelectMensesButton recordMensesFlowBtn2;
    RecordSelectMensesButton recordMensesFlowBtn3;
    RecordSelectMensesButton recordMensesFlowBtn4;
    RecordSelectMensesButton recordMensesFlowBtn5;
    RecordSelectMensesButton recordMensesColorBtn1;
    RecordSelectMensesButton recordMensesColorBtn2;
    RecordSelectMensesButton recordMensesColorBtn3;
    RecordSelectMensesButton recordMensesColorBtn4;
    RecordSelectMensesButton recordMensesColorBtn5;
    RecordOptionMensesButton recordMensesStatusBlockBtn;
    RecordOptionMensesButton recordMensesStatusOdourBtn;
    RecordOptionMensesButton recordMensesStatusDrossyBtn;
    ImageView mensesCross, mensesTick;
    ImageView copulationCross, copulationTick;
    RelativeLayout record_menses_edit_layout;
    TextView mensesHint;

    RecordSelectCopulationButton recordCopulationYesBtn;
    RecordSelectCopulationButton recordCopulationNoBtn;
    RecordSelectCopulationContentButton recordCopulationTimeBtn;
    RecordOptionCopulationButton recordCopulationContraceptionCondom;
    RecordOptionCopulationButton recordCopulationContraceptionMedicine;
    RecordOptionCopulationButton recordCopulationContraceptionOther;
    RecordOptionCopulationButton recordCopulationPositionKneeChest;
    RecordOptionCopulationButton recordCopulationPositionSupine;
    RecordOptionCopulationButton recordCopulationPositionOther;
    RelativeLayout record_copulation_edit_layout;

    RecordSelectOvulationButton recordOvulationYesBtn;
    RecordSelectOvulationButton recordOvulationNoBtn;
    RecordSelectOvulationButton recordOvulationNegativeBtn;
    RecordSelectOvulationButton recordOvulationWeakPositiveBtn;
    RecordSelectOvulationButton recordOvulationPositiveBtn;
    RecordSelectOvulationButton recordOvulationStrongPositiveBtn;
    RecordSelectOvulationContentButton recordOvulationPaperBrandBtn;
    RecordSelectOvulationContentButton recordOvulationTimeBtn;
    Button recordOvulationAddPhotoBtn;
    Button recordOvulationAddPaperBtn;
    Button recordOvulationPhotoRetakeBtn;
    Button recordOvulationPhotoDeleteBtn;
    ImageView recordOvulationHelpBtn;
    RelativeLayout record_ovulation_edit_layout;
    SwipeMenuListView recordOvuPhotoList;
    List<RecordInfo> LHItems = new ArrayList<RecordInfo>();
    List<RecordInfo> LHList = new ArrayList<RecordInfo>();
    private OvuPaperPhotoAdapter ovuPaperPhotoAdapter;

    RecordSelectEarlyPregnancyButton recordEarlyPregnancyNegativeBtn;
    RecordSelectEarlyPregnancyButton recordEarlyPregnancyWeakPositiveBtn;
    RecordSelectEarlyPregnancyButton recordEarlyPregnancyPositiveBtn;
    RecordSelectEarlyPregnancyButton recordEarlyPregnancyStrongPositiveBtn;
    SwipeMenuListView recordEarlyPregnancyList;
    EarlyPregnancyPaperPhotoAdapter earlyPregnancyPaperPhotoAdapter;
    Button recordEarlyPregnancyAddPhotoBtn;
    ImageView recordEarlyPregnancyHelpBtn;
    List<RecordInfo> HCGList = new ArrayList<RecordInfo>();
    List<RecordInfo> HCGItems = new ArrayList<RecordInfo>();
    List<RecordInfo> BUList = new ArrayList<RecordInfo>();

    RecordSelectBUltraButton recordBultraYesBtn;
    RecordSelectBUltraButton recordBultraNoBtn;
    Button recordBultraPhotoAddBtn;
    ImageView recordBultraPhoto, recordBuDel;
    RelativeLayout record_b_ultra_edit_layout;

    RecordOptionSymptomButton symptomMeasureLateBtn, symptomStayupLateBtn, symptomTripBtn, symptomJetLagBtn, symptomHolidayOutofLifeBtn, symptomWeatherChangeBtn, symptomBigPressureBtn, symptomTooExcitedBtn, symptomDrunkBtn, symptomFeverBtn, symptomSickBtn, symptomNotMensesBleedBtn, symptomDizzyBtn,
            symptomBackAcheBtn, symptomAnxiousBtn, symptomBellyAcheBtn, symptomHeadacheBtn, symptomBreastAcheBtn, symptomBodyAchesBtn;

    private EditText memeoEditText;

    private DateUtil dateUtil = new DateUtil();
    private static final int ADD_ONE_DAY = 1;
    private static final int MINUS_ONE_DAY = -1;

    public UserRecordData userRecordData = new UserRecordData();
    public List<UserTemperatureInfo> selectedDayTemper = new ArrayList<UserTemperatureInfo>();
    private List<UserTemperatureInfo> deleteDayTemper = new ArrayList<UserTemperatureInfo>();
    public static int bbtHave, mucusColor, mucusStatus, mucusFlow;
    public static int mensesBlood, mensesDysmenorrhea, mensesColor, mensesStatusBlock, mensesStatusOdour, mensesStatusDrossy, mensesFlow;
    public static int copulationHaveSex;
    private double referBBT;
    private int referMucusInfo, referMensesBlood;
    private String copulationSexTime;
    private String memo;
    public static int mensesInfo, mucusInfo, viewNum, copulationInfo, symptomTemperInfo;
    public static int viewPosition = 0;
    private String dateRecord;
    private VerticalViewPager verticalViewPager;
    private VerticalAdapter verticalAdapter;
    View bbtView, mucusView, mensesView, copulationView, ovulationView, earlypregnancyView, bUltraView, symptomView, memoView;
    List<View> pageViews;
    //private WebView webview;
    private int mensesHintValue = 0;  //显示姨妈来了为1， 显示姨妈走了为0
    private int mensesChoiceValue = 0;  //选择是为1， 选择否为0
    private int referMensesChoiceValue = 0;

    private JSONArray jsonArrayCycleDatas, jsonArrayUserDatas;
    private JSONObject jsonObjectUserData;
    private Algorithm algorithm;
    private boolean isAlgorithmUsed = false;
    private boolean isMensesAlgorithmUsed = false;
    private boolean isDeleteSinglePS = false;
    private String lastPeriodDateValue;

    private DBManager dbManager;
    private String picBUNameID = null;
    private String date;
    private int LHResult = 0;
    private int HCGResult = 0;
    private int LHdelete = 0;
    private int HCGdelete = 0;
    private int BUdelete = 0;
    private Bitmap BUBitmap = null;
    private UserRecordData originRecordData = new UserRecordData();
    private List<Double> originDayTempers = new ArrayList<Double>();

    private boolean testPaperIsChanged = false;//判断所有试纸部分是否有改动
    private boolean isToday = true;//判断是否为今天
    private String beChangedDate = null;//被更改后的日期

    private ProgressDialog progressDialog;

    public RecordFragment() {
        // Required empty public constructor
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        long t1 = System.currentTimeMillis();
        AppLog.i("get in RecordFragment start!");

        // Inflate the layout for this fragment
        viewFragment = inflater.inflate(R.layout.fragment_record, container, false);
        // 实例化tabhost
        //optimizedFragmentTabHost = (OptimizedFragmentTabHost) getActivity().findViewById(android.R.id.tabhost);
        verticalViewPager = (VerticalViewPager) viewFragment.findViewById(R.id.record_viewpager);
        dbManager = new DBManager(getActivity());
        initViewPager(inflater);
        recordRightMarksGroup = (RadioGroup) viewFragment.findViewById(R.id.record_right_marks_group);
        recordRightMarksGroup.setOnCheckedChangeListener(rightMarksCheckedListener);
        recordRightMarksGroup.check(R.id.record_right_bbt_selected_mark);
        algorithm = new Algorithm(getActivity());

        date = dateUtil.getDate();

        initView();
        initValue();

        long t2 = System.currentTimeMillis();
        AppLog.i("get in RecordFragment end! time = " + (t2 - t1));
        return viewFragment;
    }

    private void initViewPager(LayoutInflater inflater) {
        pageViews = new ArrayList<View>();
        bbtView = inflater.inflate(R.layout.record_bbt_layout, null);
        pageViews.add(bbtView);
        mucusView = inflater.inflate(R.layout.record_mucus_layout, null);
        pageViews.add(mucusView);
        mensesView = inflater.inflate(R.layout.record_menses_layout, null);
        pageViews.add(mensesView);
        copulationView = inflater.inflate(R.layout.record_copulation_layout, null);
        pageViews.add(copulationView);
        ovulationView = inflater.inflate(R.layout.record_ovulation_layout, null);
        pageViews.add(ovulationView);
        earlypregnancyView = inflater.inflate(R.layout.record_early_pregnancy_layout, null);
        pageViews.add(earlypregnancyView);
        bUltraView = inflater.inflate(R.layout.record_b_ultra_layout, null);
        pageViews.add(bUltraView);
        symptomView = inflater.inflate(R.layout.record_symptom_layout, null);
        pageViews.add(symptomView);
        memoView = inflater.inflate(R.layout.record_note_layout, null);
        pageViews.add(memoView);
        verticalAdapter = new VerticalAdapter(pageViews);
        verticalViewPager.setAdapter(verticalAdapter);
        verticalViewPager.setOnPageChangeListener(simpleOnPageChangeListener);

    }

    private void initView() {
        initTopBar(viewFragment);
        initBBTView(bbtView);
        initMucusView(mucusView);
        initMensesView(mensesView);
        initCopulationView(copulationView);
        initOvulationView(ovulationView);
        initEarlyPregnancyView(earlypregnancyView);
        initBUltraView(bUltraView);
        initSymptomView(symptomView);
        initMemoView(memoView);
        //initWebview(viewFragment);
        verticalViewPager.setCurrentItem(viewNum);
    }

    private void initValue() {

        mucusInfo = 0;//宫颈粘液值
        mucusColor = 0;//宫颈粘液颜色
        mucusStatus = 0;//宫颈粘液状态
        mucusFlow = 0;//宫颈粘液流量

        mensesInfo = 0;//月经值
        mensesBlood = 0;
        mensesDysmenorrhea = 0;
        mensesColor = 0;//月经颜色
        mensesStatusBlock = 0;
        mensesStatusOdour = 0;
        mensesStatusDrossy = 0;
        mensesFlow = 0;//月经

        memo = null;
        copulationSexTime = null;
        copulationHaveSex = 0;
        symptomTemperInfo = 0;
        copulationInfo = 0;
        referBBT = 0.0;
        referMensesBlood = 0;
        referMucusInfo = 0;
        recordTemperatureRecordBtn.setText(getResources().getString(R.string.record_bbt_temperature));

        clearMucusView();
        clearMensesView();
        clearCopulationView();
        clearSymptomView();
        hideBBTEditView();
        memeoEditText.setText(null);
        userRecordData = dbManager.getSelectedDayRecordData(App.userName, dateRecord);
        originRecordData.setMensesInfo(userRecordData.getMensesInfo());
        originRecordData.setMucusInfo(userRecordData.getMucusInfo());
        originRecordData.setCopulationInfo(userRecordData.getCopulationInfo());
        originRecordData.setMemoInfo(userRecordData.getMemoInfo());
        originRecordData.setSexTime(userRecordData.getSexTime());
        originRecordData.setSymptomInfo(userRecordData.getSymptomInfo());
        AppLog.i(userRecordData.getId());
        if (null != userRecordData.getId() && !"".equals(userRecordData.getId())) {
            mucusInfo = userRecordData.getMucusInfo();
            referMucusInfo = mucusInfo;
            AppLog.i("mucus info:" + mucusInfo);
            initMucusValue(mucusInfo);
            mensesInfo = userRecordData.getMensesInfo();
            initMensesValue(mensesInfo);
            copulationInfo = userRecordData.getCopulationInfo();
            initCopulationValue();
            symptomTemperInfo = userRecordData.getSymptomInfo();
            initSymptomValue();
            if (0 != userRecordData.getSexTime()) {
                copulationSexTime = DateUtil.getTimeStr(userRecordData.getSexTime());
                recordCopulationTimeBtn.setText(copulationSexTime);
            }
            memo = userRecordData.getMemoInfo();
            if (null != memo) memeoEditText.setText(memo);
        }
        selectedDayTemper.clear();
        deleteDayTemper.clear();
        originDayTempers.clear();
        selectedDayTemper = dbManager.getSelectedDayTemperature(App.userName, dateRecord);
        AppLog.i("selectedDayTemper:" + selectedDayTemper.size());
        if (selectedDayTemper.size() != 0) {
            selectedDayTemper.get(0).setIsBBT(1);
            sortSelectedTemper();
            referBBT = selectedDayTemper.get(0).getTemperature();
            for (int i = 0; i < selectedDayTemper.size(); i++) {
                originDayTempers.add(selectedDayTemper.get(i).getTemperature());
            }
        }
        updateTemperatureShowView();
        setCurrentRecordMensesType();
        mensesInfo = (mensesBlood) | (mensesDysmenorrhea << 5) | (mensesFlow << 2) | (mensesColor << 8) | (mensesStatusBlock << 11) | (mensesStatusOdour << 12) | (mensesStatusDrossy << 13);
        originRecordData.setMensesInfo(mensesInfo);
        referMensesBlood = mensesBlood;
    }

    private void sortSelectedTemper() {
        if (selectedDayTemper.size() > 1) {
            if (selectedDayTemper.get(0).getIsBBT() != 1) {
                for (int i = 1; i < selectedDayTemper.size(); i++) {
                    if (selectedDayTemper.get(i).getIsBBT() == 1) {
                        UserTemperatureInfo userTemperatureInfo = selectedDayTemper.get(0);
                        selectedDayTemper.set(0, selectedDayTemper.get(i));
                        selectedDayTemper.set(i, userTemperatureInfo);
                    }
                }
            }

            if (selectedDayTemper.size() > 2) {
                for (int i = 1; i < selectedDayTemper.size(); i++) {
                    for (int j = i + 1; j < selectedDayTemper.size(); j++) {
                        if (selectedDayTemper.get(j).getMeasureTime() < selectedDayTemper.get(i).getMeasureTime()) {
                            UserTemperatureInfo userTemperatureInfo = selectedDayTemper.get(i);
                            selectedDayTemper.set(i, selectedDayTemper.get(j));
                            selectedDayTemper.set(j, userTemperatureInfo);
                        }
                    }
                }
            }
        }
    }

    private void initSymptomValue() {
        //symptomMeasureLateBtn, symptomStayupLateBtn, symptomTripBtn, symptomJetLagBtn, symptomHolidayOutofLifeBtn, symptomWeatherChangeBtn, symptomBigPressureBtn, symptomTooExcitedBtn, symptomDrunkBtn,
        symptomMeasureLateBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 17));
        symptomStayupLateBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 5));
        symptomTripBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 4));
        symptomJetLagBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 18));
        symptomHolidayOutofLifeBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 19));
        symptomWeatherChangeBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 20));
        symptomBigPressureBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 21));
        symptomTooExcitedBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 22));
        symptomDrunkBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 3));
        symptomFeverBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 7));
        symptomSickBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 2));
        symptomNotMensesBleedBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 8));
        symptomDizzyBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 9));
        symptomBackAcheBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 10));
        symptomAnxiousBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 11));
        symptomBellyAcheBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 12));
        symptomHeadacheBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 13));
        symptomBreastAcheBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 14));
        symptomBodyAchesBtn.setBackgroundColor(divideBytes(symptomTemperInfo, 1, 16));
    }

    private void initCopulationValue() {

        copulationHaveSex = divideBytes(copulationInfo, 1, 0);
        if (copulationHaveSex == 1) {
            recordCopulationYesBtn.clickAction(copulationView);
            copulationTick.setImageResource(R.drawable.record_tick_white);
            copulationCross.setImageResource(R.drawable.record_copulation_cross);
        } else {
            recordCopulationNoBtn.clickAction(copulationView);
            copulationTick.setImageResource(R.drawable.record_copulation_tick);
            copulationCross.setImageResource(R.drawable.record_cross_white);
        }

        recordCopulationContraceptionCondom.setBackgroundColor(divideBytes(copulationInfo, 1, 1));
        recordCopulationContraceptionMedicine.setBackgroundColor(divideBytes(copulationInfo, 1, 2));
        recordCopulationContraceptionOther.setBackgroundColor(divideBytes(copulationInfo, 1, 3));
        recordCopulationPositionKneeChest.setBackgroundColor(divideBytes(copulationInfo, 1, 7));
        recordCopulationPositionSupine.setBackgroundColor(divideBytes(copulationInfo, 1, 8));
        recordCopulationPositionOther.setBackgroundColor(divideBytes(copulationInfo, 1, 9));

    }

    private void clearSymptomView() {
        for (int i = 0; i < RecordFragmentCommonList.symptomBtns.length; i++) {
            RecordOptionSymptomButton button = (RecordOptionSymptomButton) symptomView.findViewById(RecordFragmentCommonList.symptomBtns[i]);
            button.setBackgroundColor(0);
        }
    }

    private void hideBBTEditView() {
        record_temperature_other_temperature1_edit_layout.setVisibility(View.GONE);
        record_temperature_base_temperature_edit_layout.setVisibility(View.GONE);
        record_temperature_other_temperature2_edit_layout.setVisibility(View.GONE);
        record_temperature_other_temperature3_edit_layout.setVisibility(View.GONE);
    }

    private void clearCopulationView() {
        copulationTick.setImageResource(R.drawable.record_copulation_tick);
        copulationCross.setImageResource(R.drawable.record_cross_white);
        recordCopulationNoBtn.clickAction(copulationView);
        for (int i = 0; i < RecordFragmentCommonList.copulationContraception.length; i++) {
            RecordOptionCopulationButton button = (RecordOptionCopulationButton) copulationView.findViewById(RecordFragmentCommonList.copulationContraception[i]);
            button.setBackgroundColor(0);
        }
        for (int i = 0; i < RecordFragmentCommonList.copulationPosition.length; i++) {
            RecordOptionCopulationButton button = (RecordOptionCopulationButton) copulationView.findViewById(RecordFragmentCommonList.copulationPosition[i]);
            button.setBackgroundColor(0);
        }

        recordCopulationTimeBtn.setColor(0);
        recordCopulationTimeBtn.setText(R.string.record_copulation_time);
    }

    private void initMucusValue(int mucusInfo) {

        mucusStatus = divideBytes(mucusInfo, 3, 1);
        if (mucusStatus > 0) {
            RecordSelectMucusButton buttonStatus = (RecordSelectMucusButton) mucusView.findViewById(RecordFragmentCommonList.mucusStatusButton[mucusStatus - 1]);
            buttonStatus.clickAction(mucusView);
        }
        mucusFlow = divideBytes(mucusInfo, 3, 4);
        if (mucusFlow > 0) {
            RecordSelectMucusButton buttonFlow = (RecordSelectMucusButton) mucusView.findViewById(RecordFragmentCommonList.mucusFlowButton[mucusFlow - 1]);
            buttonFlow.clickAction(mucusView);
        }
        mucusColor = divideBytes(mucusInfo, 3, 7);
        if (mucusColor > 0) {
            RecordSelectMucusButton buttonColor = (RecordSelectMucusButton) mucusView.findViewById(RecordFragmentCommonList.mucusColorButton[mucusColor - 1]);
            buttonColor.clickAction(mucusView);
        }
    }

    private void clearMucusView() {
        recordMucusStatusDryButton.setColor(0);
        recordMucusStatusWetButton.setColor(0);
        recordMucusStatusMilkButton.setColor(0);
        recordMucusStatusWateryButton.setColor(0);
        recordMucusFlowNoButton.setColor(0);
        recordMucusFlowLessButton.setColor(0);
        recordMucusFlowAverageButton.setColor(0);
        recordMucusFlowManyButton.setColor(0);
        recordMucusColorTransparentButton.setColor(0);
        recordMucusColorWhiteButton.setColor(0);
        recordMucusColorBloodButton.setColor(0);
    }

    private void initMensesValue(int mensesInfo) {

        mensesBlood = divideBytes(mensesInfo, 2, 0);
        referMensesBlood = mensesBlood;
        if (mensesBlood == 1) {
            recordMensesYesBtn.clickAction(mensesView);
            mensesTick.setImageResource(R.drawable.record_tick_white);
            mensesCross.setImageResource(R.drawable.record_menses_cross);
        } else {
            mensesTick.setImageResource(R.drawable.record_menses_tick);
            mensesCross.setImageResource(R.drawable.record_cross_white);
            recordMensesNoBtn.clickAction(mensesView);
        }
        mensesFlow = divideBytes(mensesInfo, 3, 2);
        if (mensesFlow > 0) {
            RecordSelectMensesButton button = (RecordSelectMensesButton) mensesView.findViewById(RecordFragmentCommonList.mensesFlowBtn[mensesFlow - 1]);
            button.clickAction(mensesView);
        }
        mensesDysmenorrhea = divideBytes(mensesInfo, 3, 5);
        if (mensesDysmenorrhea > 0) {
            RecordSelectMensesButton button = (RecordSelectMensesButton) mensesView.findViewById(RecordFragmentCommonList.mensesDysmenorrheaBtn[mensesDysmenorrhea - 1]);
            button.clickAction(mensesView);
        }
        mensesColor = divideBytes(mensesInfo, 3, 8);
        if (mensesColor > 0) {
            RecordSelectMensesButton button = (RecordSelectMensesButton) mensesView.findViewById(RecordFragmentCommonList.mensesColorBtn[mensesColor - 1]);
            button.clickAction(mensesView);
        }
        mensesStatusBlock = divideBytes(mensesInfo, 1, 11);
        recordMensesStatusBlockBtn.setBackgroundColor(mensesStatusBlock);
        mensesStatusOdour = divideBytes(mensesInfo, 1, 12);
        recordMensesStatusOdourBtn.setBackgroundColor(mensesStatusOdour);
        mensesStatusDrossy = divideBytes(mensesInfo, 1, 13);
        recordMensesStatusDrossyBtn.setBackgroundColor(mensesStatusDrossy);
    }

    private void clearMensesView() {
        mensesTick.setImageResource(R.drawable.record_menses_tick);
        mensesCross.setImageResource(R.drawable.record_cross_white);
        recordMensesNoBtn.clickAction(mensesView);
        for (int i = 0; i < RecordFragmentCommonList.mensesFlowBtn.length; i++) {
            RecordSelectMensesButton button = (RecordSelectMensesButton) mensesView.findViewById(RecordFragmentCommonList.mensesFlowBtn[i]);
            button.setBackground(getResources().getDrawable(R.drawable.record_menses_flow_button_default));
        }
        for (int i = 0; i < RecordFragmentCommonList.mensesDysmenorrheaBtn.length; i++) {
            RecordSelectMensesButton button = (RecordSelectMensesButton) mensesView.findViewById(RecordFragmentCommonList.mensesDysmenorrheaBtn[i]);
            button.setBackground(getResources().getDrawable(R.drawable.record_menses_button_default));
            button.setTextColor(getResources().getColor(R.color.yjq_color));
        }
        for (int i = 0; i < RecordFragmentCommonList.mensesColorBtn.length; i++) {
            RecordSelectMensesButton button = (RecordSelectMensesButton) mensesView.findViewById(RecordFragmentCommonList.mensesColorBtn[i]);
            button.setBackground(getResources().getDrawable(RecordFragmentCommonList.mensesColorDrawable[i]));
        }

        recordMensesStatusBlockBtn.setBackgroundColor(0);
        recordMensesStatusOdourBtn.setBackgroundColor(0);
        recordMensesStatusDrossyBtn.setBackgroundColor(0);
    }

    private boolean isRecordDataChanged() {
        boolean result = false;
        boolean baseRecordInfoChanged = checkBaseRecordInfoChanged();
        boolean temperChanged = checkTemperInfoChanged();
        //检查信息是否修改
        result = baseRecordInfoChanged || temperChanged || testPaperIsChanged;
        return result;
    }

    public void checkChangeAndBackHome() {
        getRecordInfo();
        if (isRecordDataChanged()) {
            Dialog alertDialog = new AlertDialog.Builder(getActivity()).
                    setTitle(getString(R.string.warm_prompt)).
                    setMessage(getString(R.string.save_commit)).
                    setPositiveButton(getString(R.string.sure), new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            saveSelectedDayRecord();
                        }
                    }).
                    setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }

                    ).
                    create();
            alertDialog.setCancelable(false);
            alertDialog.show();
        } else {
        }

    }

    private boolean checkTemperInfoChanged() {
        boolean result = false;
        AppLog.e("originDayTempers.size():" + originDayTempers.size() + "selectedDayTemper.size():" + selectedDayTemper.size());
        if (originDayTempers.size() != selectedDayTemper.size()) return true;
        if (originDayTempers.size() > 0) {
            for (int i = 0; i < originDayTempers.size(); i++) {
                if (originDayTempers.get(i) != selectedDayTemper.get(i).getTemperature()) {
                    return true;
                }
            }
        } else return false;
        return result;
    }

    private boolean checkBaseRecordInfoChanged() {
        boolean result = false;
        if (originRecordData.getMensesInfo() != userRecordData.getMensesInfo()) return true;
        if (originRecordData.getSexTime() != userRecordData.getSexTime()) return true;
        if (originRecordData.getCopulationInfo() != userRecordData.getCopulationInfo()) return true;
        if (originRecordData.getMucusInfo() != userRecordData.getMucusInfo()) return true;
        int originSymptom = originRecordData.getSymptomInfo();
        if (0 != divideBytes(originRecordData.getSymptomInfo(), 1, 6)) {
            originSymptom -= 64;
        }
        int userSymptom = userRecordData.getSymptomInfo();
        if (0 != divideBytes(userRecordData.getSymptomInfo(), 1, 6)) {
            userSymptom -= 64;
        }
        if (originSymptom != userSymptom) return true;
        if (null != originRecordData.getMemoInfo() && null != userRecordData.getMemoInfo()) {
            if (!originRecordData.getMemoInfo().equals(userRecordData.getMemoInfo())) return true;
        } else {
            if (null != originRecordData.getMemoInfo() && !"".equals(originRecordData.getMemoInfo()) && null == userRecordData.getMemoInfo())
                return true;
            if (null == originRecordData.getMemoInfo() && null != userRecordData.getMemoInfo() && !"".equals(userRecordData.getMemoInfo()))
                return true;
        }
        return result;
    }

    private int divideBytes(int value, int bits, int position) {

        return (value >> position) & (int) (Math.pow(2, bits) - 1);
    }

    private void initTopBar(final View view) {
        topBar = (TopBar) view.findViewById(R.id.topBar);
        topBar.setText(dateUtil.getDateTopBar());
        if (!"".equals(MainActivity.chosedDateCalendar))
            topBar.setText(DateUtil.getCircleCalendarTopDate(DateUtil.getStringToDate(MainActivity.chosedDateCalendar + " 00:00:00")));
        dateRecord = topBar.getText().split(" ")[0];
        AppLog.i("dateRecord = " + dateRecord);
//        StatusBarColor(dateRecord);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                AppLog.i("leftClick clicked!");
                //checkChangeAndBackHome();

                //强制隐藏键盘
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
            }

            @Override
            public void midLeftClick() {
                getRecordInfo();
                if (isRecordDataChanged()) {
                    Dialog alertDialog = new AlertDialog.Builder(getActivity()).
                            setTitle(getString(R.string.warm_prompt)).
                            setMessage(getString(R.string.save_commit)).
                            setPositiveButton(getString(R.string.sure), new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    saveSelectedDayRecord();
                                }
                            }).
                            setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                            changeTopBarDate(MINUS_ONE_DAY);
                                            dateRecord = topBar.getText().split(" ")[0];
                                            StatusBarColor(dateRecord);
                                            initValue();
                                        }
                                    }

                            ).
                            create();
                    alertDialog.setCancelable(false);
                    alertDialog.show();
                } else {
                    changeTopBarDate(MINUS_ONE_DAY);
                    dateRecord = topBar.getText().split(" ")[0];
                    StatusBarColor(dateRecord);
                    initValue();
                }

            }

            @Override
            public void midRightClick() {
                isToday = false;
                getRecordInfo();
                if (isRecordDataChanged()) {
                    Dialog alertDialog = new AlertDialog.Builder(getActivity()).
                            setTitle(getString(R.string.warm_prompt)).
                            setMessage(getString(R.string.save_commit)).
                            setPositiveButton(getString(R.string.sure), new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    saveSelectedDayRecord();
                                }
                            }).
                            setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                            changeTopBarDate(ADD_ONE_DAY);
                                            dateRecord = topBar.getText().split(" ")[0];
                                            StatusBarColor(dateRecord);
                                            initValue();
                                        }
                                    }

                            ).
                            create();
                    alertDialog.setCancelable(false);
                    alertDialog.show();
                } else {
                    changeTopBarDate(ADD_ONE_DAY);
                    dateRecord = topBar.getText().split(" ")[0];
                    StatusBarColor(dateRecord);
                    initValue();
                }
            }

            @Override
            public void rightClick() {
//                saveLHAndHCGAndBU();
                saveSelectedDayRecord();
            }
        });
    }

    private void saveSelectedDayRecord() {
        long currentTime = DateUtil.getStringToDate(DateUtil.getCurrentDay() + " 00:00:00");
        long recordDateZeroTime = DateUtil.getStringToDate(dateRecord + " 00:00:00");
        if (recordDateZeroTime > currentTime) {
            Toast.makeText(getActivity(), R.string.edit_record_information_future, Toast.LENGTH_SHORT).show();
            return;
        }
        CycleUnitDS[] cycleUnitDS = dbManager.getAllMensesConfirmStartHaveALCycleOutput(App.userName);
        if(mensesHintValue == 1 && referMensesChoiceValue == 1 && mensesBlood == 0 && cycleUnitDS.length == 1 && cycleUnitDS[0].menstruationStartConfirm == DateUtil.getStringToDate(dateRecord + " 12:00:00")){
                showInputLastPeriodDateDialog();
        }else{
            getRecordInfo();
            if (!isRecordDataChanged()) {
                Toast.makeText(getActivity(), R.string.record_information_no_change, Toast.LENGTH_SHORT).show();
                return;
            }

            showProgressDialog();

            saveLHAndHCGAndBU();
            syncAndUploadRecordDatas();
        }

    }

    private void backHomeFragment() {
        //optimizedFragmentTabHost.setCurrentTab(0);

        isToday = true;

        LHList = dbManager.getNeedSyncedRecordLH("LHPaperID");
        for (int i = 0; i < LHList.size(); i++) {
            if (LHList.get(i).getLHIsDelete() == 0 && LHList.get(i).getLHIsSynced() == 0) {
                dbManager.updateRecordLH(LHList.get(i).getLHPaperID(), 1, 0);
            }
        }

        HCGList = dbManager.getNeedSyncedRecordHCG("HCGPaperID");
        for (int i = 0; i < HCGList.size(); i++) {
            if (HCGList.get(i).getHCGIsDelete() == 0 && HCGList.get(i).getHCGIsSynced() == 0) {
                dbManager.updateRecordHCG(HCGList.get(i).getHCGPaperID(), 1, 0);
            }
        }

        BUList = dbManager.getNeedSyncedRecordBU("BUID");
        if (BUList.size() != 0 && BUList.get(0).getBUIsDelete() == 0 && BUList.get(0).getBUIsSynced() == 0) {
            dbManager.updateRecordBU(BUList.get(0).getBUID(), 1, 0);
        }
    }

    private void showProgressDialog() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(getString(R.string.saving));
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void showInputLastPeriodDateDialog() {

        Dialog alertDialog = new AlertDialog.Builder(getActivity()).
                setTitle(getString(R.string.warm_prompt)).
                setMessage(getString(R.string.menstruation_another_enter_again)).
                setPositiveButton(getString(R.string.sure), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setDateDialog();
                    }
                }).
                create();
        alertDialog.setCancelable(false);
        alertDialog.show();
    }

    private void setDateDialog() {
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        int year = calendar.get(java.util.Calendar.YEAR);
        int monthofYear = calendar.get(java.util.Calendar.MONTH);
        int dayofMonth = calendar.get(java.util.Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String setLastPeriodDate = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                if (DateUtil.isFutureDate(year + "/" + (monthOfYear + 1) + "/" + dayOfMonth)) {
                    Toast.makeText(getActivity(), getString(R.string.future_time), Toast.LENGTH_SHORT).show();
                } else {
                    lastPeriodDateValue = setLastPeriodDate;
                    App.memory_preference_lastPeriodDate = setLastPeriodDate;
                    dbManager.updateUserPreference(App.userName, "lastPeriodDate", setLastPeriodDate);
                    userRecordData.setMensesInfo(0);
                    userRecordData.setIsSynced(0);
                    dbManager.saveRecordData(userRecordData);
                    UserRecordData userRecordData1 = dbManager.getSelectedDayRecordData(App.userName, setLastPeriodDate);
                    if (null != userRecordData1.getId() && !"".equals(userRecordData1.getId())) {
                        userRecordData1.setMensesInfo(1);
                        userRecordData1.setIsSynced(0);
                        dbManager.saveRecordData(userRecordData1);
                    } else {
                        userRecordData1.setId(UUID.randomUUID().toString());
                        userRecordData1.setRecordDate(DateUtil.getStringToDate(setLastPeriodDate + " 12:00:00"));
                        userRecordData1.setUserName(App.userName);
                        userRecordData1.setMensesInfo(1);
                        userRecordData1.setIsSynced(0);
                        dbManager.saveRecordData(userRecordData1);
                    }
                    AppLog.e("changeMensesStart is isAlgorithmUsed!");
                    g1Tog2Algorithm();
                    dbManager.initDayUnitDSOutputsList2Memory(App.userName);
                    AlgoUpdateMsg algoUpdateMsg = new AlgoUpdateMsg();
                    algoUpdateMsg.setRespCode(1);
                    EventBus.getDefault().post(algoUpdateMsg);
                    StatusBarColor(dateRecord);
                    initValue();
                }
            }
        }, year, monthofYear, dayofMonth);
        dialog.setCancelable(false);
        DatePicker datePicker = dialog.getDatePicker();
        datePicker.setMaxDate(new Date().getTime());
        dialog.show();
    }

    private void uploadRecordInfo() {

        getRecordInfo();
        if (selectedDayTemper.size() > 0 || deleteDayTemper.size() > 0) { // 给userRecordData中封装体温数据
            UserTemperatureInfo[] userTemperatureInfos = new UserTemperatureInfo[selectedDayTemper.size() + deleteDayTemper.size()];
            if (selectedDayTemper.size() > 0) {
                for (int i = 0; i < selectedDayTemper.size(); i++) {
                    userTemperatureInfos[i] = selectedDayTemper.get(i);
                }
                if (deleteDayTemper.size() > 0) {
                    for (int i = selectedDayTemper.size(); i < (selectedDayTemper.size() + deleteDayTemper.size()); i++) {
                        userTemperatureInfos[i] = deleteDayTemper.get(i - selectedDayTemper.size());
                    }
                }
                userRecordData.setUserTemperatureInfos(userTemperatureInfos);

            } else {
                for (int i = 0; i < deleteDayTemper.size(); i++) {
                    userTemperatureInfos[i] = deleteDayTemper.get(i);
                }

                userRecordData.setUserTemperatureInfos(userTemperatureInfos);
            }
        }

        JSONArray jsonArray = new JSONArray();
        jsonArray.put(userRecordData.getUserRecordDataInfoJson());
        AppLog.i("authToken = " + App.authToken + ", jsonArray = " + jsonArray.toString());
        OKHttpUtil okHttpClient = new OKHttpUtil(RecordFragment.this.getActivity());
        String appendUrl = "sync/addSignsRecords.json";
        try {

            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("records", jsonArray);

            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    saveRecordData(0);
                    saveTemperatureRecord(0);
                    syncAndUpdateCycleDatas(0);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {

                    try {
                        String str = response.body().string();
                        AppLog.i("addSignsRecords response:" + str);
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");
                        if (App.HTTP_RESP_OK == respCode) {
                            AppLog.i("addSignsRecords onResponse success!");
                            saveRecordData(1);
                            saveTemperatureRecord(1);
                            syncAndUpdateCycleDatas(1);
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                            temperUploadMsg.setUpdateCode(App.HTTP_RESP_TOKEN_TIME_OUT);
                            EventBus.getDefault().post(temperUploadMsg);
                        } else {
                            AppLog.i("addSignsRecords onResponse failed! respCode = " + respCode);
                            saveRecordData(0);
                            saveTemperatureRecord(0);
                            syncAndUpdateCycleDatas(0);
                        }
                    } catch (JSONException e) {
                        saveRecordData(0);
                        saveTemperatureRecord(0);
                        syncAndUpdateCycleDatas(0);
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            saveRecordData(0);
            saveTemperatureRecord(0);
            syncAndUpdateCycleDatas(0);
            AppLog.i("UploadCycleData JSONException!");
            e.printStackTrace();
        }

    }

    private void syncAndUploadRecordDatas() {
        if (InternetUtil.hasInternet()) {
            SyncRecordInfoMsg syncRecordInfoMsg = new SyncRecordInfoMsg();
            syncRecordInfoMsg.setSyncInActivity(SyncALDataMsg.SYNC_IN_RECORDFRAGMENT);
            SyncRecordInfo syncRecordInfo = new SyncRecordInfo(getActivity(), syncRecordInfoMsg);
            AppLog.e("SyncRecordInfoWithNetwork");
            syncRecordInfo.syncRecordInfoWithNetwork();
        } else {
            AppLog.e("syncAndUploadRecordDatas");
                    uploadRecordInfo();
        }
    }

    @Subcriber
    private void syncRecordDataInRecordActivity(SyncRecordInfoMsg syncRecordInfoMsg) {
        if (syncRecordInfoMsg.getSyncInActivity().equals(SyncRecordInfoMsg.SYNC_RECORD_IN_RECORDFRAGMENT)) {
            AppLog.e("App.syncRecordDataInRecordActivity");
            uploadRecordInfo();
        }
    }

    private void syncAndUpdateCycleDatas(int isSynced) {
        if (InternetUtil.hasInternet()) {
            SyncALDataMsg syncALDataMsg = new SyncALDataMsg();
            syncALDataMsg.setSyncInActivity(SyncALDataMsg.SYNC_IN_RECORDFRAGMENT);

            SyncALData syncALData = new SyncALData(getActivity(), syncALDataMsg);
            AppLog.e("SyncALDataWithNetwork");
            syncALData.SyncALDataWithNetwork();
        } else {
            AppLog.e("syncAndUpdateCycleDatas!");
            updateCycleDatas(isSynced);
        }
    }

    @Subcriber
    private void syncRecordChangeALData(SyncALDataMsg syncALDataMsg) {
        if (syncALDataMsg.getSyncInActivity().equals(SyncALDataMsg.SYNC_IN_RECORDFRAGMENT)) {
            if (algorithm != null) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        AppLog.e("updateCycleDatas(1)!");
                        updateCycleDatas(1);
                    }
                }).start();
            }
        }
    }

//    private void updateCycleDatas(int isSynced) {
//        long recordDaySeconds = DateUtil.getStringToDate(dateRecord + " 00:00:00");
//        //long firstCycleUnitDSMensesStartConfirm = dbManager.getFirstCycleUnitDSMensesStartConfirm(App.userName);
//
//        if (referMensesBlood == 0 && mensesBlood == 1) {
//            AppLog.i("algorithm Menses");
//            algorithm.executeAL(7, algorithm.getMensesDayInput(recordDaySeconds, 7), algorithm.getMensesCycleInput(7), isSynced);
//            referMensesBlood = mensesBlood;
//            isAlgorithmUsed = true;
//        }
//        if (mensesBlood == 0 && referMensesBlood == 1) {
//            AppLog.i("algorithm Menses2");
//
//            if (!checkMenses15DayStatus()) {
//                AppLog.i("algorithm Menses2 !checkMensesNineDay");
//                algorithm.executeAL(4, algorithm.getMensesDayInput(recordDaySeconds, 4), algorithm.getMensesCycleInput(4), isSynced);
//                isAlgorithmUsed = true;
//            } else {
//                algorithm.executeAL(7, algorithm.getMensesDayInput(recordDaySeconds, 7), algorithm.getMensesCycleInput(7), isSynced);
//                isAlgorithmUsed = true;
//            }
//            referMensesBlood = mensesBlood;
//        }
//        if ((selectedDayTemper.size() > 0) && (referBBT != selectedDayTemper.get(0).getTemperature())) {
//            AppLog.i("algorithm bbt");
//            algorithm.executeAL(11, algorithm.getBBTDayInput(), algorithm.getBBTMucusCycleInput(), isSynced);
//            referBBT = selectedDayTemper.get(0).getTemperature();
//            isAlgorithmUsed = true;
//        }
//        if (mucusInfo != 0 && mucusInfo != referMucusInfo) {
//            AppLog.i("algorithm mucus");
//            if (null == algorithm) AppLog.e("null is algorithm---------------------------");
//            else AppLog.e("NOT null is algorithm---------------------------");
//            algorithm.executeAL(12, algorithm.getMucusDayInput(), algorithm.getBBTMucusCycleInput(), isSynced);
//            referMucusInfo = mucusInfo;
//            isAlgorithmUsed = true;
//        }
//        if (isAlgorithmUsed) {
//            isAlgorithmUsed = false;
//            jsonArrayCycleDatas = algorithm.getCycleOutputJson();
//            jsonArrayUserDatas = algorithm.getDayOutputJson();
//            jsonObjectUserData = algorithm.getUserInfoJson();
//            dbManager.initDayUnitDSOutputsList2Memory(App.userName);
//            AlgoUpdateMsg algoUpdateMsg = new AlgoUpdateMsg();
//            algoUpdateMsg.setRespCode(1);
//            EventBus.getDefault().post(algoUpdateMsg);
//            if (isSynced == 1)
//                uploadCycleDatas();
//            else {
//                TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
//                temperUploadMsg.setUpdateCode(2);
//                EventBus.getDefault().post(temperUploadMsg);
//            }
//        } else {
//            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
//            temperUploadMsg.setUpdateCode(2);
//            EventBus.getDefault().post(temperUploadMsg);
//        }
//    }

    /**
     * 姨妈来了调用的算法
     *
     *wzz 算法
     *
     * @param isSynced
     */
    private void updateCycleDatas(int isSynced) {
        long recordDaySeconds = DateUtil.getStringToDate(dateRecord + " 00:00:00");
        AppLog.e("start algorithm in recordFragment");
            if(mensesHintValue == 1 && referMensesChoiceValue == 0 && mensesBlood == 1){//1姨妈来了/0走了   初始状态下的选择按钮（1选择开关打开/0关闭）      点击后的状态值
                AppLog.i("algorithm Menses inputStart");
                int result = algorithm.executeAL(2, algorithm.getMensesDayInput(recordDaySeconds, 2), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
                if(result == 234) g1Tog2Algorithm();
                long currentDayCycleUnitDSMensesStartConfirm = dbManager.getSelectedDayCycleUnitDSMensesStartConfirm(App.userName, new Date().getTime() / 1000);
                AppLog.e("currentDayCycleUnitDSMensesStartConfirm:" + currentDayCycleUnitDSMensesStartConfirm);
                long periodAchieveConfirm = dbManager.getSelectedDayALDayUnitDSOutput(App.userName, currentDayCycleUnitDSMensesStartConfirm).periodAchieveConfirm;
                AppLog.e("periodAchieveConfirm:" + periodAchieveConfirm);
                if(periodAchieveConfirm == 0){
                    changeForecastStart();
                }
                isAlgorithmUsed = true;
                isMensesAlgorithmUsed = true;
            }
            if(mensesHintValue == 0 && referMensesChoiceValue == 0 && mensesBlood == 1){
                AppLog.i("algorithm Menses inputEnd");
                int result = algorithm.executeAL(3, algorithm.getMensesDayInput(recordDaySeconds, 3), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
                if(result == 234) g1Tog2Algorithm();
                isAlgorithmUsed = true;
                isMensesAlgorithmUsed = true;
            }
            if(mensesHintValue == 1 && referMensesChoiceValue == 1 && mensesBlood == 0){
                AppLog.i("algorithm Menses deleteStart");
                int result = algorithm.executeAL(4, algorithm.getMensesDayInput(recordDaySeconds, 4), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
                if(result == 234) g1Tog2Algorithm();
                long currentDayCycleUnitDSMensesStartConfirm = dbManager.getSelectedDayCycleUnitDSMensesStartConfirm(App.userName, new Date().getTime() / 1000);
                AppLog.e("currentDayCycleUnitDSMensesStartConfirm:" + currentDayCycleUnitDSMensesStartConfirm);
                long periodAchieveConfirm = dbManager.getSelectedDayALDayUnitDSOutput(App.userName, currentDayCycleUnitDSMensesStartConfirm).periodAchieveConfirm;
                AppLog.e("periodAchieveConfirm:" + periodAchieveConfirm);
                if(periodAchieveConfirm == 0){
                    changeForecastStart();
                }
                isAlgorithmUsed = true;
                isMensesAlgorithmUsed = true;
            }
            if(mensesHintValue == 0 && referMensesChoiceValue == 1 && mensesBlood == 0){
                AppLog.i("algorithm Menses deleteEnd");
                int result = algorithm.executeAL(5, algorithm.getMensesDayInput(recordDaySeconds, 5), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
                if(result == 234) g1Tog2Algorithm();
                isAlgorithmUsed = true;
                isMensesAlgorithmUsed = true;
            }

        /**
         * 温度算法有关
         */
        long currentDayCycleUnitDSMensesStartConfirm = dbManager.getSelectedDayCycleUnitDSMensesStartConfirm(App.userName, new Date().getTime()/1000);//（取今天的时间）当前周期的经期开始时间
        AppLog.e("currentDayCycleUnitDSMensesStartConfirm:" + currentDayCycleUnitDSMensesStartConfirm);
        long firstMensesStartConfirm = dbManager.getCycleUnitDSMensesFirstStartConfirm(App.userName);//整个算法数据中的第一个经期开始时间
        AppLog.e("firstMensesStartConfirm:" + firstMensesStartConfirm);
        if(currentDayCycleUnitDSMensesStartConfirm < recordDaySeconds ){
            if ((selectedDayTemper.size() > 0) && (referBBT != selectedDayTemper.get(0).getTemperature())) {
                AppLog.i("algorithm bbt");
                int result = algorithm.executeAL(11, algorithm.getBBTDayInput(), algorithm.getBBTMucusCycleInput(), isSynced);
                if(result == 234) g1Tog2Algorithm();
                referBBT = selectedDayTemper.get(0).getTemperature();
                isAlgorithmUsed = true;
            }
        }else{
            if((firstMensesStartConfirm > 0 && recordDaySeconds >firstMensesStartConfirm)){
                if ((selectedDayTemper.size() > 0) && (referBBT != selectedDayTemper.get(0).getTemperature())) {
                    AppLog.i("algorithm bbt history");
                    int result = algorithm.executeAL(23, algorithm.getHistoryBBTDayInput(recordDaySeconds), algorithm.getHistoryBBTCycleInput(recordDaySeconds), isSynced);
                    if(result == 234) g1Tog2Algorithm();
                    referBBT = selectedDayTemper.get(0).getTemperature();
                    isAlgorithmUsed = true;
                }
            }
        }

        if (mucusInfo != 0 && mucusInfo != referMucusInfo) {
            AppLog.i("algorithm mucus");
            int result = algorithm.executeAL(12, algorithm.getMucusDayInput(), algorithm.getBBTMucusCycleInput(), isSynced);
            if(result == 234) g1Tog2Algorithm();
            referMucusInfo = mucusInfo;
            isAlgorithmUsed = true;
        }

        if (isAlgorithmUsed) {
            isAlgorithmUsed = false;
            jsonArrayCycleDatas = algorithm.getCycleOutputJson();
            jsonArrayUserDatas = algorithm.getDayOutputJson();
            jsonObjectUserData = algorithm.getUserInfoJson();
            dbManager.initDayUnitDSOutputsList2Memory(App.userName);
            AlgoUpdateMsg algoUpdateMsg = new AlgoUpdateMsg();
            algoUpdateMsg.setRespCode(1);
            EventBus.getDefault().post(algoUpdateMsg);
            if (isSynced == 1)
                uploadCycleDatas();
            else {
                AppLog.e("msg at is not synced!");
                TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                temperUploadMsg.setUpdateCode(2);
                EventBus.getDefault().post(temperUploadMsg);
            }
        } else {
            AppLog.e("msg at is not isAlgorithmUsed!");
            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
            temperUploadMsg.setUpdateCode(2);
            EventBus.getDefault().post(temperUploadMsg);
        }
    }

    //算法返回值为234时调用一代转二代
    private void g1Tog2Algorithm(){
        UserUnitDS userData = new UserUnitDS();
        userData.averageMenstruationLength = App.memory_preference_mensesLen;
        userData.averageCycleLength = App.memory_preference_periodLen;
        DayUnitDSInput[] dayInput = dbManager.getDayInputListFromG1Record(App.userName);
        algorithm.g1FirstLoginG2(userData, dayInput, 0);
        checkIfNeedDealHistoryData();
    }

    private void checkIfNeedDealHistoryData() {
        CycleUnitDS[] cycleUnitDSes = dbManager.getALCycleOutput(App.userName, null);
        if(null != cycleUnitDSes && cycleUnitDSes.length > 0){
            for(int i = 0; i < cycleUnitDSes.length; i++){
                cycleUnitDSes[i].ovulationDayUserRecordBasis = -99;
            }
            dbManager.saveALCycleOutput(cycleUnitDSes, 0);
        }

        List<DayUnitDSOutput> dayUnitDSOutputs = dbManager.getALDayUnitDSOutputList(App.userName);
        if(null != dayUnitDSOutputs && dayUnitDSOutputs.size() > 0){
            for(int i = 0; i < dayUnitDSOutputs.size(); i++){
                dayUnitDSOutputs.get(i).periodAchieveForecast = 99;
            }
                    dbManager.saveALDayOutput(dayUnitDSOutputs, 0);
        }
        saveALResult2Sqlite(0);
    }

    private void saveALResult2Sqlite(int isSynced) {
        algorithm.saveALData2Sqlite(isSynced);
    }

    private void changeForecastStart() {
        long zeroTime = DateUtil.getDateZeroTime2bit(new Date().getTime() / 1000) - 12 * 3600;
        int result = algorithm.executeAL(7, algorithm.getChangeForecastMensesStartDayInput(zeroTime), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), 0);
        if(result == 234) g1Tog2Algorithm();
    }

    private boolean checkMenses9DayStatus() {
        boolean result = false;
        long startTime = DateUtil.getStringToDate(dateRecord + " 00:00:00") - 9 * 24 * 3600;
        long endTime = DateUtil.getStringToDate(dateRecord + " 23:59:59") + 9 * 24 * 3600;
        List<UserRecordData> userRecordDataList = dbManager.getRecordDataList(App.userName, startTime, endTime);
        if (userRecordDataList.size() != 0) {
            for (int i = 0; i < userRecordDataList.size(); i++) {
                if (divideBytes(userRecordDataList.get(i).getMensesInfo(), 2, 0) == 1) {
                    result = true;
                    break;
                }
            }
        } else {
            result = false;
        }

        return result;
    }

    private boolean checkMenses15DayStatus() {
        boolean result = false;
        long startTime = DateUtil.getStringToDate(dateRecord + " 00:00:00") - 14 * 24 * 3600;
        long endTime = DateUtil.getStringToDate(dateRecord + " 00:00:00");
        List<UserRecordData> userRecordDataList = dbManager.getRecordDataList(App.userName, startTime, endTime);
        if (userRecordDataList.size() != 0) {
            for (int i = 0; i < userRecordDataList.size(); i++) {
                if (divideBytes(userRecordDataList.get(i).getMensesInfo(), 2, 0) == 1) {
                    result = true;
                    break;
                }
            }
        } else {
            long startTime1 = DateUtil.getStringToDate(dateRecord + " 00:00:00");
            long endTime1 = DateUtil.getStringToDate(dateRecord + " 23:59:59") + 14 * 24 * 3600;
            List<UserRecordData> userRecordDataList1 = dbManager.getRecordDataList(App.userName, startTime1, endTime1);
            if (userRecordDataList1.size() != 0) {
                for (int i = 0; i < userRecordDataList1.size(); i++) {
                    if (divideBytes(userRecordDataList1.get(i).getMensesInfo(), 2, 0) == 1) {
                        result = true;
                        break;
                    }
                }
            } else
                result = false;
        }

        return result;
    }

    private void saveTemperatureRecord(int isSynced) {

        if (selectedDayTemper.size() > 0) {
            for (int i = 0; i < selectedDayTemper.size(); i++) {
                selectedDayTemper.get(i).setSyncType(isSynced);
                dbManager.saveTempearatureData(selectedDayTemper.get(i));
            }
        }
        if (deleteDayTemper.size() > 0) {
            for (int i = 0; i < deleteDayTemper.size(); i++) {
                deleteDayTemper.get(i).setSyncType(isSynced);
                dbManager.saveTempearatureData(deleteDayTemper.get(i));
            }
        }
    }

    private void saveRecordData(int isSynced) {
        userRecordData.setIsSynced(isSynced);
        dbManager.saveRecordData(userRecordData);

        if (userRecordData.getMensesInfo() == 0 && originRecordData.getMensesInfo() != 0) {
            if (null != dbManager.getLastMensesRecordData(App.userName)) {
                App.memory_preference_lastPeriodDate = DateUtil.getDateStr2bit(dbManager.getLastMensesRecordData(App.userName).getRecordDate());
                dbManager.updateUserPreference(App.userName, "lastPeriodDate", App.memory_preference_lastPeriodDate);
            }
        } else if (userRecordData.getMensesInfo() != 0) {
            if (null != dbManager.getLastMensesRecordData(App.userName)) {
                App.memory_preference_lastPeriodDate = DateUtil.getDateStr2bit(dbManager.getLastMensesRecordData(App.userName).getRecordDate());
                dbManager.updateUserPreference(App.userName, "lastPeriodDate", App.memory_preference_lastPeriodDate);
            }
        }

//        if (null != App.memory_preference_lastPeriodDate && !"".equals(App.memory_preference_lastPeriodDate)) {
//            if (userRecordData.getMensesInfo() != 0 && userRecordData.getRecordDate() > DateUtil.getStringToDate(App.memory_preference_lastPeriodDate + " 23:59:59")) {
//                dbManager.updateUserPreference(App.userName, "lastPeriodDate", DateUtil.getDateStr2bit(userRecordData.getRecordDate()));
//                App.memory_preference_lastPeriodDate = DateUtil.getDateStr2bit(userRecordData.getRecordDate());
//            }
//        } else {
//            if (userRecordData.getMensesInfo() != 0) {
//                dbManager.updateUserPreference(App.userName, "lastPeriodDate", DateUtil.getDateStr2bit(userRecordData.getRecordDate()));
//                App.memory_preference_lastPeriodDate = DateUtil.getDateStr2bit(userRecordData.getRecordDate());
//            }
//        }
    }

    private void getRecordInfo() {

        if ("".equals(userRecordData.getId()) || null == userRecordData.getId()) {
            userRecordData.setId(UUID.randomUUID().toString());
        }

        userRecordData.setUserName(App.userName);

        if (selectedDayTemper.size() == 0) bbtHave = 0;
        else bbtHave = 1;

        if (0 == userRecordData.getRecordDate())
            userRecordData.setRecordDate(DateUtil.getStringToDate(dateRecord + " " + recordTemperatureTimeBtn.getText().toString() + ":00"));
        else userRecordData.setRecordEditDate(new Date().getTime() / 1000);

        mucusInfo = (mucusStatus << 1) | (mucusFlow << 4) | (mucusColor << 7);
        AppLog.i("mucusInfo:" + Integer.toBinaryString(mucusInfo));
        userRecordData.setMucusInfo(mucusInfo);

        mensesInfo = (mensesBlood) | (mensesDysmenorrhea << 5) | (mensesFlow << 2) | (mensesColor << 8) | (mensesStatusBlock << 11) | (mensesStatusOdour << 12) | (mensesStatusDrossy << 13);
        AppLog.i("mensesInfo:" + Integer.toBinaryString(mensesInfo));
        userRecordData.setMensesInfo(mensesInfo);

        if (null != memeoEditText.getText())
            userRecordData.setMemoInfo(memeoEditText.getText().toString());

        if (null != recordCopulationTimeBtn.getText() && !getResources().getString(R.string.record_copulation_time).equals(recordCopulationTimeBtn.getText().toString())) {
            userRecordData.setSexTime(DateUtil.getStringToDate(dateRecord + " " + recordCopulationTimeBtn.getText().toString() + ":00"));
        }

        copulationInfo = copulationHaveSex | (recordCopulationContraceptionCondom.getBackgroundColor() << 1) | (recordCopulationContraceptionMedicine.getBackgroundColor() << 2) |
                (recordCopulationContraceptionOther.getBackgroundColor() << 3) | (recordCopulationPositionKneeChest.getBackgroundColor() << 7) | (recordCopulationPositionSupine.getBackgroundColor() << 8) |
                (recordCopulationPositionOther.getBackgroundColor() << 9);
        userRecordData.setCopulationInfo(copulationInfo);

        symptomTemperInfo = (bbtHave << 6) | (symptomSickBtn.getBackgroundColor() << 2) | (symptomDrunkBtn.getBackgroundColor() << 3) | (symptomTripBtn.getBackgroundColor() << 4) | (symptomFeverBtn.getBackgroundColor() << 7) |
                (symptomNotMensesBleedBtn.getBackgroundColor() << 8) | (symptomDizzyBtn.getBackgroundColor() << 9) | (symptomBackAcheBtn.getBackgroundColor() << 10) | (symptomAnxiousBtn.getBackgroundColor() << 11) |
                (symptomMeasureLateBtn.getBackgroundColor() << 17) | (symptomStayupLateBtn.getBackgroundColor() << 5) | (symptomJetLagBtn.getBackgroundColor() << 18) | (symptomHolidayOutofLifeBtn.getBackgroundColor() << 19) | (symptomWeatherChangeBtn.getBackgroundColor() << 20) | (symptomBigPressureBtn.getBackgroundColor() << 21) | (symptomTooExcitedBtn.getBackgroundColor() << 22) |
                (symptomBellyAcheBtn.getBackgroundColor() << 12) | (symptomHeadacheBtn.getBackgroundColor() << 13) | (symptomBreastAcheBtn.getBackgroundColor() << 14) | (symptomBodyAchesBtn.getBackgroundColor() << 16);
        userRecordData.setSymptomInfo(symptomTemperInfo);
    }

    /**
     * 保存所有试纸信息
     * <p/>
     * 试纸保存逻辑（本地数据库，isDelete表示是否删除，1为删除，0为未删除；isSynced表示是否已同步至数据库，1为已上传，0为未上传）
     * 1、拍试纸照片时，将本地数据库中所对应的该图片的isDelete和isSynced置为0；
     * 2、拍试纸照片后不对其进行保存，则isDelete：1、isSynced：0；
     * 3、拍照后保存，则isDelete：0、isSynced：1。
     */
    private void saveLHAndHCGAndBU() {
        String appendUrl = "gyna/addCheckGynas.json";
        OKHttpUtil okHttpClient = new OKHttpUtil(RecordFragment.this.getActivity());
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("LHs", LHJson());
            okHttpClient.add("HCGs", HCGJson());
            okHttpClient.add("BUs", BUJson());
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            uploadGynaImgGetDate();
                        } else if (App.HTTP_RESP_TOKEN_TIME_OUT == respCode) {
                            OKHttpUtil.setNewToken();
                            saveLHAndHCGAndBU();
                        } else if(respCode == 215){
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                                progressDialog = null;
                            }
                        }
                    } catch (JSONException e) {
                        AppLog.i("add Check Gynas failed! e = " + e);
                        e.printStackTrace();
                    }
                }

                private void sendNOKResp(TasksUtil tasksUtil) {
                    EventBus.getDefault().post(tasksUtil);
                }

                private void sendOKResp(TasksUtil tasksUtil) {
                    EventBus.getDefault().post(tasksUtil);
                }

                private void sendNOKRespTokenTimeOut(TasksUtil tasksUtil) {
                    EventBus.getDefault().post(tasksUtil);
                }
            });
        } catch (JSONException e) {
            AppLog.i("add Check Gynas failed! e = " + e);
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        AppLog.i("LifeCycle get in RecordFragment onResume!");
    }

    @Override
    public void onPause() {
        super.onPause();
        AppLog.i("LifeCycle get in RecordFragment onPause!");

        // 215 多账号登陆时跳转至LoginActivity时取消掉dialog，否则再次登陆进来仍然可以看到此dialog
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    /**
     * 封装json数据   LH
     *
     * @return
     */
    private JSONArray LHJson() {
        JSONArray LHJsonArray = null;
        try {
            LHJsonArray = new JSONArray();
            LHList = dbManager.getNeedSyncedRecordLH("LHPaperID");
            for (int i = 0; i < LHList.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("LHPaperID", LHList.get(i).getLHPaperID());
                jsonObject.put("LHImgName", LHList.get(i).getLHPaperID());
                jsonObject.put("LHDate", LHList.get(i).getLHDate());
                jsonObject.put("LHResult", LHResult);
                jsonObject.put("LHBrand", 1);
                jsonObject.put("LHdelete", LHList.get(i).getLHIsDelete());
                LHJsonArray.put(jsonObject);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return LHJsonArray;
    }

    /**
     * 封装json数据   HCG
     *
     * @return
     */
    private JSONArray HCGJson() {
        JSONArray HCGJsonArray = null;
        try {
            HCGJsonArray = new JSONArray();
            HCGList = dbManager.getNeedSyncedRecordHCG("HCGPaperID");
            for (int i = 0; i < HCGList.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("HCGPaperID", HCGList.get(i).getHCGPaperID());
                jsonObject.put("HCGImgName", HCGList.get(i).getHCGPaperID());
                jsonObject.put("HCGDate", HCGList.get(i).getHCGDate());
                jsonObject.put("HCGResult", HCGResult);
                jsonObject.put("HCGBrand", 1);
                jsonObject.put("HCGdelete", HCGList.get(i).getHCGIsDelete());
                HCGJsonArray.put(jsonObject);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return HCGJsonArray;
    }

    /**
     * 封装json数据   BU
     *
     * @return
     */
    private JSONArray BUJson() {
        JSONArray BUJsonArray = null;
        try {
            BUJsonArray = new JSONArray();

            BUList = dbManager.getNeedSyncedRecordBU("BUID");
            for (int i = 0; i < BUList.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("BUltraID", BUList.get(i).getBUID());
                jsonObject.put("BUImgName", BUList.get(i).getBUID());
                jsonObject.put("BUDate", BUList.get(i).getBUDate());
                jsonObject.put("endomeThickness", 2.3);
                jsonObject.put("leftOvary", 1.1);
                jsonObject.put("rightOvary", 1.1);
                jsonObject.put("leftFollicle", 1.1);
                jsonObject.put("leftFollicle", 1.1);
                jsonObject.put("hospital", this.getString(R.string.beijing_hospital));
                jsonObject.put("BUdelete", BUList.get(i).getBUIsDelete());
                BUJsonArray.put(jsonObject);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return BUJsonArray;
    }

    /**
     * 将图片转换为bytes64，并保存至服务器
     */
    private void uploadGynaImgGetDate() {
        String pathString;
        String img64;
        for (int i = 0; i < LHList.size(); i++) {
            pathString = getContext().getExternalFilesDir(null).getAbsolutePath() + "/" + "PlayCamera" + "/" + LHList.get(i).getLHImgName() + ".jpg";
            img64 = getBitmap(pathString);
            uploadGynaImg(LHList.get(i).getLHImgName(), LHList.get(i).getLHDate(), img64, 1);
        }
        for (int i = 0; i < HCGList.size(); i++) {
            pathString = getContext().getExternalFilesDir(null).getAbsolutePath() + "/" + "PlayCamera" + "/" + HCGList.get(i).getHCGImgName() + ".jpg";
            img64 = getBitmap(pathString);
            uploadGynaImg(HCGList.get(i).getHCGImgName(), HCGList.get(i).getHCGDate(), img64, 2);
        }
        for (int i = 0; i < BUList.size(); i++) {
            pathString = getContext().getExternalFilesDir(null).getAbsolutePath() + "/" + BUList.get(i).getBUImgName() + ".jpg";
            img64 = getBitmap(BUBitmap);
            uploadGynaImg(BUList.get(i).getBUImgName(), BUList.get(i).getBUDate(), img64, 3);
        }
        if (BUBitmap != null && !BUBitmap.isRecycled())
            BUBitmap.recycle();

        testPaperIsChanged = false;
    }

    /**
     * 将图片转换为bytes64
     *
     * @param pathString
     * @return
     */
    private String getBitmap(String pathString) {
        Bitmap bitmap = null;
        String img64 = null;
        try {
            File file = new File(pathString);
            if (file.exists()) {
                bitmap = BitmapFactory.decodeFile(pathString);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte[] bytes = stream.toByteArray();
                img64 = new String(Base64.encodeToString(bytes, Base64.DEFAULT));
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return img64;
    }

    private String getBitmap(Bitmap bitmap) {
        String img64 = null;
        try {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
            stream.flush();
            stream.close();
            byte[] bytes = stream.toByteArray();
            img64 = new String(Base64.encodeToString(bytes, Base64.DEFAULT));
        } catch (Exception e) {
            // TODO: handle exception
        }
        return img64;
    }

    /**
     * 上传试纸图片至服务器
     *
     * @param imgName
     * @param date
     * @param img     bytes64
     * @param type    1：LH   2：HCG   3：BU
     */
    private void uploadGynaImg(final String imgName, final String date, final String img, final int type) {
        String appendUrl = "gyna/uploadGynaImg.json";
        OKHttpUtil okHttpClient = new OKHttpUtil(RecordFragment.this.getActivity());
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("imgName", imgName);
            okHttpClient.add("date", date);
            okHttpClient.add("img", img);
            okHttpClient.add("type", type);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            updateGynaeDB();
                        } else if (App.HTTP_RESP_TOKEN_TIME_OUT == respCode) {
                            OKHttpUtil.setNewToken();
                            uploadGynaImg(imgName, date, img, type);
                        } else {

                        }
                    } catch (JSONException e) {
                        AppLog.i("upload failed! e = " + e);
                        e.printStackTrace();
                    }
                }

            });
        } catch (JSONException e) {
            AppLog.i("upload failed! e = " + e);
            e.printStackTrace();
        }
    }

    /**
     * 上传图片至服务器后更新本地数据库，设置idDelete为0，isSynced为1
     */
    private void updateGynaeDB() {
        LHList = dbManager.getNeedSyncedRecordLH("LHPaperID");
        for (int i = 0; i < LHList.size(); i++) {
            if (LHList.get(i).getLHIsDelete() == 0 && LHList.get(i).getLHIsSynced() == 0) {
                dbManager.updateRecordLH(LHList.get(i).getLHPaperID(), 0, 1);
            }
        }

        HCGList = dbManager.getNeedSyncedRecordHCG("HCGPaperID");
        for (int i = 0; i < HCGList.size(); i++) {
            if (HCGList.get(i).getHCGIsDelete() == 0 && HCGList.get(i).getHCGIsSynced() == 0) {
                dbManager.updateRecordHCG(HCGList.get(i).getHCGPaperID(), 0, 1);
            }
        }

        BUList = dbManager.getNeedSyncedRecordBU("BUID");
        if (BUList.size() != 0 && BUList.get(0).getBUIsDelete() == 0 && BUList.get(0).getBUIsSynced() == 0) {
            dbManager.updateRecordBU(BUList.get(0).getBUID(), 0, 1);
        }
    }

    public void setDateFromCalendar(String dateString) {
        long DayCalendar = DateUtil.getStringToDate(dateString + " 00:00:00");
        long CurrentDay = DateUtil.getStringToDate(dateRecord + " 00:00:00");
        int diifer = (int) (DayCalendar - CurrentDay) / (24 * 3600);
        changeTopBarDate(diifer);
        dateRecord = topBar.getText().split(" ")[0];
//        StatusBarColor(dateRecord);
        initValue();
    }

    @Subcriber
    public void reflish(RecordChange recordChange) {
        setDateFromCalendar(recordChange.getString());
    }

    /**
     * topbar选择日期
     *
     * @param oneDay
     */
    private void changeTopBarDate(int oneDay) {
        AppLog.i("change TopBar date!");
        try {
            changeGynaeForDate(oneDay);
            topBar.setText(dateUtil.getDateAddOrMinus(topBar.getText(), oneDay));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 跟随topbar的时间改变，试纸图片对应改变
     *
     * @param oneDay
     */
    private void changeGynaeForDate(int oneDay) {
        try {
            beChangedDate = dateUtil.getSimpleDateAddOrMinus(topBar.getText(), oneDay);
            initTestPaperMsg(beChangedDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化LH试纸
     *
     * @param view
     */
    private void initOvulationView(View view) {
        recordOvulationYesBtn = (RecordSelectOvulationButton) view.findViewById(R.id.record_ovulation_btn_yes);
        recordOvulationYesBtn.setOnClickListener(ovulationClickListener);
        recordOvulationNoBtn = (RecordSelectOvulationButton) view.findViewById(R.id.record_ovulation_btn_no);
        recordOvulationNoBtn.setOnClickListener(ovulationClickListener);
        recordOvulationNegativeBtn = (RecordSelectOvulationButton) view.findViewById(R.id.record_ovulation_test_result_negative);
        recordOvulationNegativeBtn.setOnClickListener(ovulationClickListener);
        recordOvulationWeakPositiveBtn = (RecordSelectOvulationButton) view.findViewById(R.id.record_ovulation_test_result_weak_positive);
        recordOvulationWeakPositiveBtn.setOnClickListener(ovulationClickListener);
        recordOvulationPositiveBtn = (RecordSelectOvulationButton) view.findViewById(R.id.record_ovulation_test_result_positive);
        recordOvulationPositiveBtn.setOnClickListener(ovulationClickListener);
        recordOvulationStrongPositiveBtn = (RecordSelectOvulationButton) view.findViewById(R.id.record_ovulation_test_result_strong_positive);
        recordOvulationStrongPositiveBtn.setOnClickListener(ovulationClickListener);
        recordOvulationPaperBrandBtn = (RecordSelectOvulationContentButton) view.findViewById(R.id.record_ovulation_paper_brand_btn);
        recordOvulationPaperBrandBtn.setOnClickListener(ovulationClickListener);
        recordOvulationTimeBtn = (RecordSelectOvulationContentButton) view.findViewById(R.id.record_ovulation_time_btn);
        recordOvulationTimeBtn.setOnClickListener(ovulationClickListener);
        record_ovulation_edit_layout = (RelativeLayout) view.findViewById(R.id.record_ovulation_edit_layout);
        recordOvulationAddPhotoBtn = (Button) view.findViewById(R.id.record_ovulation_add_photo_btn);
        recordOvulationAddPhotoBtn.setOnClickListener(ovulationClickListener);
        recordOvulationAddPaperBtn = (Button) view.findViewById(R.id.record_ovulation_add_paper_btn);
        recordOvulationAddPaperBtn.setOnClickListener(ovulationClickListener);
        recordOvulationPhotoRetakeBtn = (Button) view.findViewById(R.id.record_ovulation_btn_photo_retake);
        recordOvulationPhotoRetakeBtn.setOnClickListener(ovulationClickListener);
        recordOvulationPhotoDeleteBtn = (Button) view.findViewById(R.id.record_ovulation_btn_photo_delete);
        recordOvulationPhotoDeleteBtn.setOnClickListener(ovulationClickListener);
        recordOvulationHelpBtn = (ImageView) view.findViewById(R.id.record_ovulation_question_icon);
        recordOvulationHelpBtn.setOnClickListener(ovulationClickListener);

        recordOvuPhotoList = (SwipeMenuListView) view.findViewById(R.id.record_ovulation_photo_list);

        initLHPaperMsg(date.substring(0, 10));

        LHSwipeMenuManager();
    }

    /**
     * 初始化HCG
     *
     * @param view
     */
    private void initEarlyPregnancyView(View view) {
        recordEarlyPregnancyNegativeBtn = (RecordSelectEarlyPregnancyButton) view.findViewById(R.id.record_early_pregnancy_test_result_negative);
        recordEarlyPregnancyNegativeBtn.setOnClickListener(earlyPregnancyClickListener);
        recordEarlyPregnancyWeakPositiveBtn = (RecordSelectEarlyPregnancyButton) view.findViewById(R.id.record_early_pregnancy_test_result_weak_positive);
        recordEarlyPregnancyWeakPositiveBtn.setOnClickListener(earlyPregnancyClickListener);
        recordEarlyPregnancyPositiveBtn = (RecordSelectEarlyPregnancyButton) view.findViewById(R.id.record_early_pregnancy_test_result_positive);
        recordEarlyPregnancyPositiveBtn.setOnClickListener(earlyPregnancyClickListener);
        recordEarlyPregnancyStrongPositiveBtn = (RecordSelectEarlyPregnancyButton) view.findViewById(R.id.record_early_pregnancy_test_result_strong_positive);
        recordEarlyPregnancyStrongPositiveBtn.setOnClickListener(earlyPregnancyClickListener);
        recordEarlyPregnancyAddPhotoBtn = (Button) view.findViewById(R.id.record_early_pregnancy_add_photo_btn);
        recordEarlyPregnancyAddPhotoBtn.setOnClickListener(earlyPregnancyClickListener);
        recordEarlyPregnancyHelpBtn = (ImageView) view.findViewById(R.id.record_early_pregnancy_question_icon);
        recordEarlyPregnancyHelpBtn.setOnClickListener(earlyPregnancyClickListener);

        recordEarlyPregnancyList = (SwipeMenuListView) view.findViewById(R.id.record_early_pregnancy_photo_list);

        initHCGPaperMsg(date.substring(0, 10));

        HCGSwipeMenuManager();
    }

    /**
     * 左滑删除部分
     */
    private void LHSwipeMenuManager() {
//        SwipeMenuCreator creator = new SwipeMenuCreator() {
//
//            @Override
//            public void create(SwipeMenu menu) {
//                SwipeMenuItem deleteItem = new SwipeMenuItem(getContext());
//                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
//                deleteItem.setWidth(dp2px(90));
//                deleteItem.setTitle(getString(R.string.record_bbt_delete));
//                deleteItem.setTitleSize(18);
//                deleteItem.setTitleColor(Color.WHITE);
////                deleteItem.setIcon(R.drawable.ic_delete);
//                menu.addMenuItem(deleteItem);
//            }
//        };
//
//        //LH试纸左滑删除
//        recordOvuPhotoList.setMenuCreator(creator);
//        recordOvuPhotoList.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
//            @Override
//            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
//                switch (index) {
//                    case 0:
//                        dbManager.updateRecordLH(LHItems.get(position).getLHPaperID(), 1, 0);
//                        LHItems.remove(position);
//                        ovuPaperPhotoAdapter.notifyDataSetChanged();
//                        testPaperIsChanged = true;
//                        break;
//                }
//            }
//        });
//
//        recordOvuPhotoList.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {
//            @Override
//            public void onSwipeStart(int position) {
//            }
//
//            @Override
//            public void onSwipeEnd(int position) {
//            }
//        });

        recordOvuPhotoList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                Dialog alertDialog = new AlertDialog.Builder(getActivity()).
                        setTitle(getString(R.string.warm_prompt)).
                        setMessage(getString(R.string.del_test_paper)).
                        setPositiveButton(getString(R.string.sure), new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dbManager.updateRecordLH(LHItems.get(position).getLHPaperID(), 1, 0);
                                LHItems.remove(position);
                                ovuPaperPhotoAdapter.notifyDataSetChanged();
                                testPaperIsChanged = true;
                            }
                        }).
                        setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }
                        ).
                        create();
                alertDialog.setCancelable(false);
                alertDialog.show();

                return false;
            }
        });
    }

    private void HCGSwipeMenuManager() {
//        SwipeMenuCreator creator = new SwipeMenuCreator() {
//
//            @Override
//            public void create(SwipeMenu menu) {
//                SwipeMenuItem deleteItem = new SwipeMenuItem(getContext());
//                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
//                deleteItem.setWidth(dp2px(90));
//                deleteItem.setTitle(getString(R.string.record_bbt_delete));
//                deleteItem.setTitleSize(18);
//                deleteItem.setTitleColor(Color.WHITE);
////                deleteItem.setIcon(R.drawable.ic_delete);
//                menu.addMenuItem(deleteItem);
//            }
//        };
//        //HCG试纸左滑删除
//        recordEarlyPregnancyList.setMenuCreator(creator);
//
//        recordEarlyPregnancyList.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
//            @Override
//            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
//                switch (index) {
//                    case 0:
//                        dbManager.updateRecordHCG(HCGItems.get(position).getHCGPaperID(), 1, 0);
//                        HCGItems.remove(position);
//                        earlyPregnancyPaperPhotoAdapter.notifyDataSetChanged();
//                        testPaperIsChanged = true;
//                        break;
//                }
//            }
//        });
//
//        recordEarlyPregnancyList.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {
//            @Override
//            public void onSwipeStart(int position) {
//            }
//
//            @Override
//            public void onSwipeEnd(int position) {
//            }
//        });

        recordEarlyPregnancyList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                Dialog alertDialog = new AlertDialog.Builder(getActivity()).
                        setTitle(getString(R.string.warm_prompt)).
                        setMessage(getString(R.string.del_test_paper)).
                        setPositiveButton(getString(R.string.sure), new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dbManager.updateRecordHCG(HCGItems.get(position).getHCGPaperID(), 1, 0);
                                HCGItems.remove(position);
                                earlyPregnancyPaperPhotoAdapter.notifyDataSetChanged();
                                testPaperIsChanged = true;
                            }
                        }).
                        setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }
                        ).
                        create();
                alertDialog.setCancelable(false);
                alertDialog.show();
                return false;
            }
        });
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    /**
     * 初始化B超
     *
     * @param view
     */
    private void initBUltraView(View view) {
        recordBultraYesBtn = (RecordSelectBUltraButton) view.findViewById(R.id.record_b_ultra_btn_yes);
        recordBultraYesBtn.setOnClickListener(bUltraClickListener);
        recordBultraNoBtn = (RecordSelectBUltraButton) view.findViewById(R.id.record_b_ultra_btn_no);
        recordBultraNoBtn.setOnClickListener(bUltraClickListener);
        record_b_ultra_edit_layout = (RelativeLayout) view.findViewById(R.id.record_b_ultra_edit_layout);
        recordBultraPhotoAddBtn = (Button) view.findViewById(R.id.record_b_ultra_btn_photo_add);
        recordBultraPhotoAddBtn.setOnClickListener(bUltraClickListener);
        recordBultraPhoto = (ImageView) view.findViewById(R.id.record_b_ultra_photo);
        recordBultraPhoto.setOnClickListener(bUltraClickListener);
        recordBuDel = (ImageView) view.findViewById(R.id.record_b_ultra_photo_trash);
        recordBuDel.setOnClickListener(bUltraClickListener);

        initBUPaperMsg(date);

    }

    private void initSymptomView(View view) {

        symptomMeasureLateBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_measure_late_btn);
        symptomStayupLateBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_stay_up_late_btn);
        symptomTripBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_trip_btn);
        symptomJetLagBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_jet_leg_btn);
        symptomHolidayOutofLifeBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_holiday_loss_life_btn);
        symptomWeatherChangeBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_weather_change_btn);
        symptomBigPressureBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_big_pressure_btn);
        symptomTooExcitedBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_too_excited_btn);
        symptomDrunkBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_drunk_btn);
        symptomFeverBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_fever_btn);
        symptomSickBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_sick_btn);
        symptomNotMensesBleedBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_blood_btn);
        symptomDizzyBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_dizzy_btn);
        symptomBackAcheBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_backache_btn);
        symptomAnxiousBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_anxious_btn);
        symptomBellyAcheBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_bellyache_btn);
        symptomHeadacheBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_headache_btn);
        symptomBreastAcheBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_breast_tenderness_btn);

        symptomBodyAchesBtn = (RecordOptionSymptomButton) view.findViewById(R.id.record_symptom_body_aches_btn);
    }

    private void initMemoView(View view) {
        memeoEditText = (EditText) view.findViewById(R.id.record_note_edit);
    }

    private void initCopulationView(View view) {
        recordCopulationYesBtn = (RecordSelectCopulationButton) view.findViewById(R.id.record_copulation_btn_yes);
        recordCopulationYesBtn.setOnClickListener(copulationClickListener);
        recordCopulationNoBtn = (RecordSelectCopulationButton) view.findViewById(R.id.record_copulation_btn_no);
        recordCopulationNoBtn.setOnClickListener(copulationClickListener);
        recordCopulationTimeBtn = (RecordSelectCopulationContentButton) view.findViewById(R.id.record_copulation_time_btn);
        recordCopulationTimeBtn.setOnClickListener(copulationClickListener);
        recordCopulationContraceptionCondom = (RecordOptionCopulationButton) view.findViewById(R.id.record_copulation_contraception_condom);
        recordCopulationContraceptionMedicine = (RecordOptionCopulationButton) view.findViewById(R.id.record_copulation_contraception_medicine);
        recordCopulationContraceptionOther = (RecordOptionCopulationButton) view.findViewById(R.id.record_copulation_contraception_other);
        recordCopulationPositionKneeChest = (RecordOptionCopulationButton) view.findViewById(R.id.record_copulation_knee_chest_position);
        recordCopulationPositionSupine = (RecordOptionCopulationButton) view.findViewById(R.id.record_copulation_supine_position);
        recordCopulationPositionOther = (RecordOptionCopulationButton) view.findViewById(R.id.record_copulation_other_position);
        record_copulation_edit_layout = (RelativeLayout) view.findViewById(R.id.record_copulation_edit_layout);
        copulationCross = (ImageView) view.findViewById(R.id.record_copulation_cross);
        copulationTick = (ImageView) view.findViewById(R.id.record_copulation_tick);
    }

    private void initBBTView(View view) {
        bbtText = (TextView) view.findViewById(R.id.record_temperature_base_temperature_record);
        bbtTimeText = (TextView) view.findViewById(R.id.record_temperature_base_temperature_time);
        otherTemperature1TimeText = (TextView) view.findViewById(R.id.record_temperature_other_temperature1_time);
        otherTemperature1Text = (TextView) view.findViewById(R.id.record_temperature_other_temperature1_record);
        otherTemperature2TimeText = (TextView) view.findViewById(R.id.record_temperature_other_temperature2_time);
        otherTemperature2Text = (TextView) view.findViewById(R.id.record_temperature_other_temperature2_record);
        otherTemperature3TimeText = (TextView) view.findViewById(R.id.record_temperature_other_temperature3_time);
        otherTemperature3Text = (TextView) view.findViewById(R.id.record_temperature_other_temperature3_record);
        record_temperature_edit_layout = (RelativeLayout) view.findViewById(R.id.record_temperature_edit_layout);
        record_temperature_base_temperature_layout = (LinearLayout) view.findViewById(R.id.record_temperature_base_temperature_layout);
        record_temperature_base_temperature_layout.setOnClickListener(bbtClickListener);
        record_temperature_base_temperature_edit_layout = (LinearLayout) view.findViewById(R.id.record_temperature_base_temperature_edit_layout);
        record_bbt_base_temperature_edit_btn = (Button) view.findViewById(R.id.record_temperature_base_temperature_edit_btn);
        record_bbt_base_temperature_edit_btn.setOnClickListener(bbtClickListener);
        record_bbt_other_temperature1_edit_btn = (Button) view.findViewById(R.id.record_temperature_other_temperature1_edit_btn);
        record_bbt_other_temperature1_edit_btn.setOnClickListener(bbtClickListener);
        record_bbt_other_temperature2_edit_btn = (Button) view.findViewById(R.id.record_temperature_other_temperature2_edit_btn);
        record_bbt_other_temperature2_edit_btn.setOnClickListener(bbtClickListener);
        record_bbt_other_temperature3_edit_btn = (Button) view.findViewById(R.id.record_temperature_other_temperature3_edit_btn);
        record_bbt_other_temperature3_edit_btn.setOnClickListener(bbtClickListener);
        record_bbt_base_temperature_delete_btn = (Button) view.findViewById(R.id.record_temperature_base_temperature_delete_btn);
        record_bbt_base_temperature_delete_btn.setOnClickListener(bbtClickListener);
        record_bbt_other_temperature1_delete_btn = (Button) view.findViewById(R.id.record_temperature_other_temperature1_delete_btn);
        record_bbt_other_temperature1_delete_btn.setOnClickListener(bbtClickListener);
        record_bbt_other_temperature2_delete_btn = (Button) view.findViewById(R.id.record_temperature_other_temperature2_delete_btn);
        record_bbt_other_temperature2_delete_btn.setOnClickListener(bbtClickListener);
        record_bbt_other_temperature3_delete_btn = (Button) view.findViewById(R.id.record_temperature_other_temperature3_delete_btn);
        record_bbt_other_temperature3_delete_btn.setOnClickListener(bbtClickListener);
        record_bbt_other_temperature1_changebbt_btn = (Button) view.findViewById(R.id.record_temperature_other_temperature1_tobbt_btn);
        record_bbt_other_temperature1_changebbt_btn.setOnClickListener(bbtClickListener);
        record_bbt_other_temperature2_changebbt_btn = (Button) view.findViewById(R.id.record_temperature_other_temperature2_tobbt_btn);
        record_bbt_other_temperature2_changebbt_btn.setOnClickListener(bbtClickListener);
        record_bbt_other_temperature3_changebbt_btn = (Button) view.findViewById(R.id.record_temperature_other_temperature3_tobbt_btn);
        record_bbt_other_temperature3_changebbt_btn.setOnClickListener(bbtClickListener);
        record_temperature_other_temperature1_layout = (LinearLayout) view.findViewById(R.id.record_temperature_other_temperature1_layout);
        record_temperature_other_temperature1_layout.setOnClickListener(bbtClickListener);
        record_temperature_other_temperature1_edit_layout = (LinearLayout) view.findViewById(R.id.record_temperature_other_temperature1_edit_layout);
        record_temperature_other_temperature2_layout = (LinearLayout) view.findViewById(R.id.record_temperature_other_temperature2_layout);
        record_temperature_other_temperature2_layout.setOnClickListener(bbtClickListener);
        record_temperature_other_temperature2_edit_layout = (LinearLayout) view.findViewById(R.id.record_temperature_other_temperature2_edit_layout);
        record_temperature_other_temperature3_layout = (LinearLayout) view.findViewById(R.id.record_temperature_other_temperature3_layout);
        record_temperature_other_temperature3_layout.setOnClickListener(bbtClickListener);
        record_temperature_other_temperature3_edit_layout = (LinearLayout) view.findViewById(R.id.record_temperature_other_temperature3_edit_layout);
        recordTemperatureRecordBtn = (RecordSelectBBTContentButton) view.findViewById(R.id.record_temperature_add_temperature_btn);
        recordTemperatureRecordBtn.setOnClickListener(bbtClickListener);
        recordTemperatureTimeBtn = (RecordSelectBBTContentButton) view.findViewById(R.id.record_temperature_add_time_btn);
        recordTemperatureTimeBtn.setOnClickListener(bbtClickListener);
        recordTemperatureTimeBtn.setText(DateUtil.getCurrentTime());
        recordTemperatureConfirmAddBtn = (Button) view.findViewById(R.id.record_temperature_add_confirm_btn);
        recordTemperatureConfirmAddBtn.setOnClickListener(bbtClickListener);
        record_bbt_layout = view.findViewById(R.id.record_temperature_layout);
        updateTemperatureShowView();
    }

    private void updateTemperatureShowView() {

        if (selectedDayTemper.size() == 0) {
            record_temperature_base_temperature_layout.setVisibility(View.GONE);
            record_temperature_other_temperature1_layout.setVisibility(View.GONE);
            record_temperature_other_temperature2_layout.setVisibility(View.GONE);
            record_temperature_other_temperature3_layout.setVisibility(View.GONE);
        }
        if (selectedDayTemper.size() == 1) {
            record_temperature_base_temperature_layout.setVisibility(View.VISIBLE);
            record_temperature_other_temperature1_layout.setVisibility(View.GONE);
            record_temperature_other_temperature2_layout.setVisibility(View.GONE);
            record_temperature_other_temperature3_layout.setVisibility(View.GONE);
            showTemper(1);
        }
        if (selectedDayTemper.size() == 2) {
            record_temperature_base_temperature_layout.setVisibility(View.VISIBLE);
            record_temperature_other_temperature1_layout.setVisibility(View.VISIBLE);
            record_temperature_other_temperature2_layout.setVisibility(View.GONE);
            record_temperature_other_temperature3_layout.setVisibility(View.GONE);
            showTemper(2);
        }
        if (selectedDayTemper.size() == 3) {
            record_temperature_base_temperature_layout.setVisibility(View.VISIBLE);
            record_temperature_other_temperature1_layout.setVisibility(View.VISIBLE);
            record_temperature_other_temperature2_layout.setVisibility(View.VISIBLE);
            record_temperature_other_temperature3_layout.setVisibility(View.GONE);
            showTemper(3);
        }
        if (selectedDayTemper.size() == 4) {
            record_temperature_base_temperature_layout.setVisibility(View.VISIBLE);
            record_temperature_other_temperature1_layout.setVisibility(View.VISIBLE);
            record_temperature_other_temperature2_layout.setVisibility(View.VISIBLE);
            record_temperature_other_temperature3_layout.setVisibility(View.VISIBLE);
            showTemper(4);
        }

    }

    private void showTemper(int i) {
        if (i >= 1) {
            bbtText.setText(String.valueOf(selectedDayTemper.get(0).getTemperature()) + "℃");
            bbtTimeText.setText(DateUtil.getTimeStr(selectedDayTemper.get(0).getMeasureTime()));
        }
        if (i >= 2) {
            otherTemperature1Text.setText(String.valueOf(selectedDayTemper.get(1).getTemperature()) + "℃");
            otherTemperature1TimeText.setText(DateUtil.getTimeStr(selectedDayTemper.get(1).getMeasureTime()));
        }
        if (i >= 3) {
            otherTemperature2Text.setText(String.valueOf(selectedDayTemper.get(2).getTemperature()) + "℃");
            otherTemperature2TimeText.setText(DateUtil.getTimeStr(selectedDayTemper.get(2).getMeasureTime()));
        }
        if (i >= 4) {
            otherTemperature3Text.setText(String.valueOf(selectedDayTemper.get(3).getTemperature()) + "℃");
            otherTemperature3TimeText.setText(DateUtil.getTimeStr(selectedDayTemper.get(3).getMeasureTime()));
        }
    }

    private void initMucusView(View view) {
        //record_mucus view
        recordMucusStatusDryButton = (RecordSelectMucusButton) view.findViewById(R.id.record_mucus_btn_dry);
        recordMucusStatusWetButton = (RecordSelectMucusButton) view.findViewById(R.id.record_mucus_btn_wet);
        recordMucusStatusMilkButton = (RecordSelectMucusButton) view.findViewById(R.id.record_mucus_btn_milky);
        recordMucusStatusWateryButton = (RecordSelectMucusButton) view.findViewById(R.id.record_mucus_btn_watery);
        recordMucusFlowNoButton = (RecordSelectMucusButton) view.findViewById(R.id.record_mucus__flow_btn_no);
        recordMucusFlowLessButton = (RecordSelectMucusButton) view.findViewById(R.id.record_mucus__flow_btn_less);
        recordMucusFlowAverageButton = (RecordSelectMucusButton) view.findViewById(R.id.record_mucus__flow_btn_average);
        recordMucusFlowManyButton = (RecordSelectMucusButton) view.findViewById(R.id.record_mucus__flow_btn_many);
        recordMucusColorTransparentButton = (RecordSelectMucusButton) view.findViewById(R.id.record_mucus_color_btn_transparent);
        recordMucusColorWhiteButton = (RecordSelectMucusButton) view.findViewById(R.id.record_mucus_color_btn_white);
        recordMucusColorBloodButton = (RecordSelectMucusButton) view.findViewById(R.id.record_mucus_color_btn_blood);
        record_mucus_layout = view.findViewById(R.id.record_mucus_layout);
        recordMucusStatusDryButton.setOnClickListener(mucusClickListener);
        recordMucusStatusWetButton.setOnClickListener(mucusClickListener);
        recordMucusStatusMilkButton.setOnClickListener(mucusClickListener);
        recordMucusStatusWateryButton.setOnClickListener(mucusClickListener);
        recordMucusFlowNoButton.setOnClickListener(mucusClickListener);
        recordMucusFlowLessButton.setOnClickListener(mucusClickListener);
        recordMucusFlowAverageButton.setOnClickListener(mucusClickListener);
        recordMucusFlowManyButton.setOnClickListener(mucusClickListener);
        recordMucusColorTransparentButton.setOnClickListener(mucusClickListener);
        recordMucusColorWhiteButton.setOnClickListener(mucusClickListener);
        recordMucusColorBloodButton.setOnClickListener(mucusClickListener);
        record_mucus_edit_layout = (RelativeLayout) view.findViewById(R.id.record_mucus_edit_layout);
    }

    private void initMensesView(View view) {
        mensesHint = (TextView) view.findViewById(R.id.record_mmenses_measure_hint);
        recordMensesYesBtn = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_btn_yes);
        recordMensesNoBtn = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_btn_no);
        recordMensesDysmenorrheaNoBtn = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_dysmenorrhea_btn_no);
        recordMensesDysmenorrheaLessBtn = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_dysmenorrhea_btn_less);
        recordMensesDysmenorrheaMiddleBtn = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_dysmenorrhea_btn_average);
        recordMensesDysmenorrheaSeroiusBtn = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_dysmenorrhea_btn_many);
        recordMensesStatusBlockBtn = (RecordOptionMensesButton) view.findViewById(R.id.record_menses_status_btn_block);
        recordMensesStatusOdourBtn = (RecordOptionMensesButton) view.findViewById(R.id.record_menses_status_btn_odour);
        recordMensesStatusDrossyBtn = (RecordOptionMensesButton) view.findViewById(R.id.record_menses_status_btn_drossy);
        record_menses_edit_layout = (RelativeLayout) view.findViewById(R.id.record_menses_edit_layout);
        recordMensesFlowBtn1 = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_flow_btn1);
        recordMensesFlowBtn1.setOnClickListener(mensesClickListener);
        recordMensesFlowBtn2 = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_flow_btn2);
        recordMensesFlowBtn2.setOnClickListener(mensesClickListener);
        recordMensesFlowBtn3 = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_flow_btn3);
        recordMensesFlowBtn3.setOnClickListener(mensesClickListener);
        recordMensesFlowBtn4 = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_flow_btn4);
        recordMensesFlowBtn4.setOnClickListener(mensesClickListener);
        recordMensesFlowBtn5 = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_flow_btn5);
        recordMensesFlowBtn5.setOnClickListener(mensesClickListener);
        recordMensesColorBtn1 = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_color_btn1);
        recordMensesColorBtn1.setOnClickListener(mensesClickListener);
        recordMensesColorBtn2 = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_color_btn2);
        recordMensesColorBtn2.setOnClickListener(mensesClickListener);
        recordMensesColorBtn3 = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_color_btn3);
        recordMensesColorBtn3.setOnClickListener(mensesClickListener);
        recordMensesColorBtn4 = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_color_btn4);
        recordMensesColorBtn4.setOnClickListener(mensesClickListener);
        recordMensesColorBtn5 = (RecordSelectMensesButton) view.findViewById(R.id.record_menses_color_btn5);
        recordMensesColorBtn5.setOnClickListener(mensesClickListener);
        recordMensesYesBtn.setOnClickListener(mensesClickListener);
        recordMensesNoBtn.setOnClickListener(mensesClickListener);
        recordMensesDysmenorrheaNoBtn.setOnClickListener(mensesClickListener);
        recordMensesDysmenorrheaLessBtn.setOnClickListener(mensesClickListener);
        recordMensesDysmenorrheaMiddleBtn.setOnClickListener(mensesClickListener);
        recordMensesDysmenorrheaSeroiusBtn.setOnClickListener(mensesClickListener);
        mensesCross = (ImageView) view.findViewById(R.id.record_menses_cross);
        mensesTick = (ImageView) view.findViewById(R.id.record_menses_tick);
    }

    /**
     * 进入记录界面 初始化部分
     */
    private void setCurrentRecordMensesType(){

        long currentRecordTime = DateUtil.getStringToDate(dateRecord + " 12:00:00");
        List<DayUnitDSOutput> dayOutputList = new ArrayList<>();
        boolean isHaveStartMenses = false;
        for(int i =  14; i >= 0; i--){
            if(null != App.DayUnitDSOutputMap.get(currentRecordTime - i * (24 * 3600))){
                dayOutputList.add(App.DayUnitDSOutputMap.get(currentRecordTime - i * (24 * 3600)));

                if(App.DayUnitDSOutputMap.get(currentRecordTime - i * (24 * 3600)).homePageNextMenstruation == 1)
                    isHaveStartMenses = true;
            }
        }

        if(dayOutputList.size() >= 10){
            if(isHaveStartMenses){
                if(dayOutputList.get(dayOutputList.size() - 2).homePageNextMenstruation == 1){
                    if(App.DayUnitDSOutputMap.get(currentRecordTime).periodAchieveConfirm >0){
                        recordMensesYesBtn.clickAction(mensesView);
                        mensesHint.setText(getString(R.string.record_menses_measure_hint));
                        mensesHintValue = 1;
                        mensesChoiceValue = 1;
                        referMensesChoiceValue = 1;
                        mensesBlood = 1;
                    }else{
                        recordMensesNoBtn.clickAction(mensesView);
                        mensesHint.setText(getString(R.string.record_menses_measure_hint));
                        mensesHintValue = 1;
                        mensesChoiceValue = 0;
                        referMensesChoiceValue = 0;
                    }
                    return;
                }

                if(App.DayUnitDSOutputMap.get(currentRecordTime).homePageNextMenstruation == 1){
                    recordMensesNoBtn.clickAction(mensesView);
                    mensesHint.setText(getString(R.string.record_menses_measure_hint));
                    mensesHintValue = 1;
                    mensesChoiceValue = 0;
                    referMensesChoiceValue = 0;
                }else{
                    boolean haveConfirmPS = false;
                    for(DayUnitDSOutput dayUnitDSOutput : dayOutputList){
                        if(dayUnitDSOutput.periodAchieveConfirm > 0){
                            haveConfirmPS = true;
                            break;
                        }
                    }
                    AppLog.e("haveConfirmPS:" + haveConfirmPS);
                    if(haveConfirmPS == false){
                        recordMensesNoBtn.clickAction(mensesView);
                        mensesHint.setText(getString(R.string.record_menses_measure_hint));
                        mensesHintValue = 1;
                        mensesChoiceValue = 0;
                        referMensesChoiceValue = 0;
                    }else{
                        if(App.DayUnitDSOutputMap.get(currentRecordTime).homePageMenstruationEnd == 0){
                            recordMensesYesBtn.clickAction(mensesView);
                            mensesHint.setText(getString(R.string.record_menses_measure_hint_no));
                            mensesHintValue = 0;
                            mensesChoiceValue = 1;
                            referMensesChoiceValue = 1;
                            AppLog.e("mensesHint 0 1 1");
                        }else {
                            recordMensesNoBtn.clickAction(mensesView);
                            mensesHint.setText(getString(R.string.record_menses_measure_hint_no));
                            mensesHintValue = 0;
                            mensesChoiceValue = 0;
                            referMensesChoiceValue = 0;
                        }

                        if(App.DayUnitDSOutputMap.get(currentRecordTime).periodAchieveForecast >0){
                            //设置确认的经期
                            //mensesBlood = 1;
                        }
                    }

                }

            }else{
                recordMensesNoBtn.clickAction(mensesView);
                mensesHint.setText(getString(R.string.record_menses_measure_hint));
                mensesHintValue = 1;
                mensesChoiceValue = 0;
                referMensesChoiceValue = 0;
            }

        }else{
            recordMensesNoBtn.clickAction(mensesView);
            mensesHint.setText(getString(R.string.record_menses_measure_hint));
            mensesHintValue = 1;
            mensesChoiceValue = 0;
            referMensesChoiceValue = 0;
        }

    }

//    private void initWebview(View view) {
//        AppLog.i("huxiao RecordFragment initWebview");
//        webview = (WebView) view.findViewById(R.id.webview);
//        WebViewCfg webViewCfg = new WebViewCfg(webview);
//        webview = webViewCfg.getCfgedWebView(view.getContext(), false);
//    }

//    private void loadWebview() {
//        if (webview != null) {
//            AppLog.i("huxiao RecordFragment loadWebview initData.html");
//
//            webview.addJavascriptInterface(new CustomerData(getActivity(), App.userName), "CustomerData");
//            webview.loadUrl("file:///android_asset/health/initData.html");
//        }
//    }

    private VerticalViewPager.SimpleOnPageChangeListener simpleOnPageChangeListener = new VerticalViewPager.SimpleOnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            recordRightMarksGroup.check(RecordFragmentCommonList.recordLeftMarkIds[position]);
        }
    };

    private RadioGroup.OnCheckedChangeListener rightMarksCheckedListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {

            for (int i = 0; i < RecordFragmentCommonList.recordLeftMarkIds.length; i++) {
                if (checkedId == RecordFragmentCommonList.recordLeftMarkIds[i]) {
                    verticalViewPager.setCurrentItem(i, true);
                    break;
                }
            }
        }
    };

    public View.OnClickListener bbtClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.record_temperature_add_temperature_btn:
                    if (App.memory_preference_macAddress == null || App.memory_preference_macAddress.length() <= 0) {
                        Toast.makeText(getContext(), R.string.toast_for_unbind, Toast.LENGTH_SHORT).show();
                    } else {
                        showTemperatureDialog(recordTemperatureRecordBtn.getText().toString(), 1);
                    }
                    return;
                case R.id.record_temperature_add_time_btn:
                    if (App.memory_preference_macAddress == null || App.memory_preference_macAddress.length() <= 0) {
                        Toast.makeText(getContext(), R.string.toast_for_unbind, Toast.LENGTH_SHORT).show();
                    } else {
                        showTimeDialog(recordTemperatureTimeBtn.getText().toString(), 1);
                    }
                    return;
                case R.id.record_temperature_base_temperature_layout:
                    if (record_temperature_base_temperature_edit_layout.isShown())
                        record_temperature_base_temperature_edit_layout.setVisibility(View.GONE);
                    else
                        record_temperature_base_temperature_edit_layout.setVisibility(View.VISIBLE);
                    record_temperature_other_temperature1_edit_layout.setVisibility(View.GONE);
                    record_temperature_other_temperature2_edit_layout.setVisibility(View.GONE);
                    record_temperature_other_temperature3_edit_layout.setVisibility(View.GONE);
                    return;
                case R.id.record_temperature_base_temperature_edit_btn:
                    showTemperatureDialog(bbtText.getText().toString(), 2);
                    return;
                case R.id.record_temperature_other_temperature1_edit_btn:
                    showTemperatureDialog(otherTemperature1Text.getText().toString(), 3);
                    return;
                case R.id.record_temperature_other_temperature2_edit_btn:
                    showTemperatureDialog(otherTemperature2Text.getText().toString(), 4);
                    return;
                case R.id.record_temperature_other_temperature3_edit_btn:
                    showTemperatureDialog(otherTemperature3Text.getText().toString(), 5);
                    return;
                case R.id.record_temperature_other_temperature1_tobbt_btn:
                    changeToBBT(1);
                    return;
                case R.id.record_temperature_other_temperature2_tobbt_btn:
                    changeToBBT(2);
                    return;
                case R.id.record_temperature_other_temperature3_tobbt_btn:
                    changeToBBT(3);
                    return;
                case R.id.record_temperature_base_temperature_delete_btn:
                    deleteTemper(0);
                    record_temperature_base_temperature_edit_layout.setVisibility(View.GONE);
                    return;
                case R.id.record_temperature_other_temperature1_delete_btn:
                    deleteTemper(1);
                    record_temperature_other_temperature1_edit_layout.setVisibility(View.GONE);
                    return;
                case R.id.record_temperature_other_temperature2_delete_btn:
                    deleteTemper(2);
                    record_temperature_other_temperature2_edit_layout.setVisibility(View.GONE);
                    return;
                case R.id.record_temperature_other_temperature3_delete_btn:
                    deleteTemper(3);
                    record_temperature_other_temperature3_edit_layout.setVisibility(View.GONE);
                    return;
                case R.id.record_temperature_other_temperature1_layout:
                    if (record_temperature_other_temperature1_edit_layout.isShown())
                        record_temperature_other_temperature1_edit_layout.setVisibility(View.GONE);
                    else
                        record_temperature_other_temperature1_edit_layout.setVisibility(View.VISIBLE);
                    record_temperature_base_temperature_edit_layout.setVisibility(View.GONE);
                    record_temperature_other_temperature2_edit_layout.setVisibility(View.GONE);
                    record_temperature_other_temperature3_edit_layout.setVisibility(View.GONE);
                    return;
                case R.id.record_temperature_other_temperature2_layout:
                    if (record_temperature_other_temperature2_edit_layout.isShown())
                        record_temperature_other_temperature2_edit_layout.setVisibility(View.GONE);
                    else
                        record_temperature_other_temperature2_edit_layout.setVisibility(View.VISIBLE);
                    record_temperature_base_temperature_edit_layout.setVisibility(View.GONE);
                    record_temperature_other_temperature1_edit_layout.setVisibility(View.GONE);
                    record_temperature_other_temperature3_edit_layout.setVisibility(View.GONE);
                    return;
                case R.id.record_temperature_other_temperature3_layout:
                    if (record_temperature_other_temperature3_edit_layout.isShown())
                        record_temperature_other_temperature3_edit_layout.setVisibility(View.GONE);
                    else
                        record_temperature_other_temperature3_edit_layout.setVisibility(View.VISIBLE);
                    record_temperature_base_temperature_edit_layout.setVisibility(View.GONE);
                    record_temperature_other_temperature2_edit_layout.setVisibility(View.GONE);
                    record_temperature_other_temperature1_edit_layout.setVisibility(View.GONE);
                    return;
                case R.id.record_temperature_add_confirm_btn:
                    if (!getResources().getString(R.string.record_bbt_temperature).equals(recordTemperatureRecordBtn.getText().toString())) {
                        record_temperature_base_temperature_layout.setVisibility(View.VISIBLE);
                        AppLog.i("record_temperature_add_confirm_btn: add");
                        if (selectedDayTemper.size() >= 4) {
                            Toast.makeText(getActivity(), R.string.bbt_morethan_four, Toast.LENGTH_LONG).show();
                            return;
                        }
                        UserTemperatureInfo userTemperatureInfo = new UserTemperatureInfo();
                        String temperature = recordTemperatureRecordBtn.getText().toString();
                        int length = temperature.indexOf("℃");
                        userTemperatureInfo.setTemperatureId(UUID.randomUUID().toString());
                        userTemperatureInfo.setUserName(App.userName);
                        userTemperatureInfo.setType(1);
                        userTemperatureInfo.setTemperature(Double.valueOf(recordTemperatureRecordBtn.getText().toString().substring(0, length)));
                        //userTemperatureInfo.setMeasureTime(new Date().getTime() / 1000);
                        userTemperatureInfo.setMeasureTime(DateUtil.getStringToDate(dateRecord + " " + recordTemperatureTimeBtn.getText().toString() + ":00"));
                        userTemperatureInfo.setEditTime(DateUtil.getStringToDate(dateRecord + " " + recordTemperatureTimeBtn.getText().toString() + ":00"));
                        if (selectedDayTemper.size() == 0) userTemperatureInfo.setIsBBT(1);
                        else userTemperatureInfo.setIsBBT(0);
                        selectedDayTemper.add(userTemperatureInfo);
                        updateTemperatureShowView();
                        recordTemperatureConfirmAddBtn.setBackground(getResources().getDrawable(R.drawable.record_temperature_button_gray));
                        recordTemperatureConfirmAddBtn.setTextColor(Color.GRAY);
                        recordTemperatureRecordBtn.setColor(RecordSelectBBTContentButton.RECORD_BBT_SELECT_CONTENT_WHITE_BACKGROUND_COLOR);
                        recordTemperatureRecordBtn.setText(getResources().getString(R.string.record_bbt_temperature));
                        recordTemperatureTimeBtn.setColor(RecordSelectBBTContentButton.RECORD_BBT_SELECT_CONTENT_WHITE_BACKGROUND_COLOR);
                        recordTemperatureTimeBtn.setText(DateUtil.getCurrentTime());
                    }
                    return;
                default:
                    return;
            }
        }
    };

    private void deleteTemper(int position) {
        selectedDayTemper.get(position).setIsDelete(1);
        deleteDayTemper.add(selectedDayTemper.get(position));
        selectedDayTemper.remove(position);
        if (position == 0 && selectedDayTemper.size() > 0)
            selectedDayTemper.get(0).setIsBBT(1);
        updateTemperatureShowView();
    }

    private void changeToBBT(int position) {
        UserTemperatureInfo userTemperatureInfo = selectedDayTemper.get(0);
        userTemperatureInfo.setIsBBT(0);
        selectedDayTemper.set(0, selectedDayTemper.get(position));
        selectedDayTemper.set(position, userTemperatureInfo);
        selectedDayTemper.get(0).setIsBBT(1);
        updateTemperatureShowView();
    }

    public View.OnClickListener mucusClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.record_mucus_btn_dry:
                case R.id.record_mucus_btn_wet:

                case R.id.record_mucus_btn_milky:
                case R.id.record_mucus_btn_watery:
                case R.id.record_mucus__flow_btn_no:
                case R.id.record_mucus__flow_btn_less:
                case R.id.record_mucus__flow_btn_average:
                case R.id.record_mucus__flow_btn_many:
                case R.id.record_mucus_color_btn_transparent:
                case R.id.record_mucus_color_btn_white:
                case R.id.record_mucus_color_btn_blood:
                    RecordSelectMucusButton button = (RecordSelectMucusButton) v;
                    button.clickAction(mucusView);
                    return;
                default:
                    return;
            }
        }
    };

    public View.OnClickListener mensesClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.record_menses_btn_yes:
                    recordMensesYesBtn.clickAction(mensesView);
                    mensesTick.setImageResource(R.drawable.record_tick_white);
                    mensesCross.setImageResource(R.drawable.record_menses_cross);
                    return;
                case R.id.record_menses_btn_no:
                    mensesTick.setImageResource(R.drawable.record_menses_tick);
                    mensesCross.setImageResource(R.drawable.record_cross_white);
                    recordMensesNoBtn.clickAction(mensesView);
//                    ();
//                    mensesInfo = 0;
//                    mensesBlood = 0;
//                    mensesDysmenorrhea = 0;
//                    mensesColor = 0;
//                    mensesFlow = 0;
//                    mensesStatusBlock = 0;
//                    mensesStatusOdour = 0;
//                    mensesStatusDrossy = 0;
                    return;
                case R.id.record_menses_dysmenorrhea_btn_no:
                case R.id.record_menses_dysmenorrhea_btn_less:
                case R.id.record_menses_dysmenorrhea_btn_average:
                case R.id.record_menses_dysmenorrhea_btn_many:
                case R.id.record_menses_flow_btn1:
                case R.id.record_menses_flow_btn2:
                case R.id.record_menses_flow_btn3:
                case R.id.record_menses_flow_btn4:
                case R.id.record_menses_flow_btn5:
                case R.id.record_menses_color_btn1:
                case R.id.record_menses_color_btn2:
                case R.id.record_menses_color_btn3:
                case R.id.record_menses_color_btn4:
                case R.id.record_menses_color_btn5:
                    RecordSelectMensesButton buttonMenses = (RecordSelectMensesButton) v;
                    buttonMenses.clickAction(mensesView);
//                    if (mensesBlood == 0) {
//                        recordMensesYesBtn.clickAction(mensesView);
//                        mensesTick.setImageResource(R.drawable.record_tick_white);
//                        mensesCross.setImageResource(R.drawable.record_menses_cross);
//                    }
                    return;
                default:
                    return;
            }
        }
    };

    public View.OnClickListener copulationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.record_copulation_btn_yes:
                    recordCopulationYesBtn.clickAction(copulationView);
                    copulationTick.setImageResource(R.drawable.record_tick_white);
                    copulationCross.setImageResource(R.drawable.record_copulation_cross);
                    return;
                case R.id.record_copulation_btn_no:
                    recordCopulationNoBtn.clickAction(copulationView);
                    copulationTick.setImageResource(R.drawable.record_copulation_tick);
                    copulationCross.setImageResource(R.drawable.record_cross_white);
                    clearCopulationView();
                    copulationInfo = 0;
                    copulationHaveSex = 0;

                    return;
                case R.id.record_copulation_time_btn:
                    showTimeDialog(recordCopulationTimeBtn.getText().toString(), 2);
                    return;
                default:
                    return;
            }

        }
    };

    public View.OnClickListener ovulationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            testPaperIsChanged = true;
            switch (v.getId()) {
                case R.id.record_ovulation_btn_yes:
                    recordOvulationYesBtn.clickAction(ovulationView);
                    record_ovulation_edit_layout.setVisibility(View.VISIBLE);
                    return;
                case R.id.record_ovulation_btn_no:
                    recordOvulationNoBtn.clickAction(ovulationView);
                    record_ovulation_edit_layout.setVisibility(View.GONE);
                    return;
                case R.id.record_ovulation_test_result_negative:
                    LHResult = 1;
                    RecordSelectOvulationButton recordSelectOvulationButton1 = (RecordSelectOvulationButton) v;
                    recordSelectOvulationButton1.clickAction(ovulationView);
                    break;
                case R.id.record_ovulation_test_result_weak_positive:
                    LHResult = 2;
                    RecordSelectOvulationButton recordSelectOvulationButton2 = (RecordSelectOvulationButton) v;
                    recordSelectOvulationButton2.clickAction(ovulationView);
                    break;
                case R.id.record_ovulation_test_result_positive:
                    LHResult = 3;
                    RecordSelectOvulationButton recordSelectOvulationButton3 = (RecordSelectOvulationButton) v;
                    recordSelectOvulationButton3.clickAction(ovulationView);
                    break;
                case R.id.record_ovulation_test_result_strong_positive:
                    LHResult = 4;
                    RecordSelectOvulationButton recordSelectOvulationButton4 = (RecordSelectOvulationButton) v;
                    recordSelectOvulationButton4.clickAction(ovulationView);
                    return;
                case R.id.record_ovulation_time_btn:
                    recordOvulationTimeBtn.clickAction(ovulationView);
                    showTimeDialog(recordOvulationTimeBtn.getText().toString(), 3);
                    return;
                case R.id.record_ovulation_paper_brand_btn:
                    recordOvulationPaperBrandBtn.clickAction(ovulationView);
                    showBrandDialog();
                    return;
                case R.id.record_ovulation_add_photo_btn:
                    takePaperPhoto();
                    return;
                case R.id.record_ovulation_add_paper_btn:
//                    LHItems.add("15:32\n大卫");
                    ovuPaperPhotoAdapter.notifyDataSetChanged();
                    fixListViewHeight(recordOvuPhotoList);
                    return;
                case R.id.record_ovulation_btn_photo_retake:
                    takePaperPhoto();
                    return;
                case R.id.record_ovulation_btn_photo_delete:
                    LHItems.clear();
                    ovuPaperPhotoAdapter.notifyDataSetChanged();
                    fixListViewHeight(recordOvuPhotoList);
                    return;
                case R.id.record_ovulation_question_icon:
                    Intent helpCenterIntent = new Intent(getActivity(), TestPaperHelpActivity.class);
                    helpCenterIntent.putExtra("testPaperType", "LH");
                    startActivity(helpCenterIntent);
                default:
                    return;
            }
        }
    };

    public View.OnClickListener earlyPregnancyClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            testPaperIsChanged = true;
            switch (v.getId()) {
                case R.id.record_early_pregnancy_test_result_negative:
                    HCGResult = 1;
                    RecordSelectEarlyPregnancyButton recordSelectEarlyPregnancyButton1 = (RecordSelectEarlyPregnancyButton) v;
                    recordSelectEarlyPregnancyButton1.clickAction(earlypregnancyView);
                    break;
                case R.id.record_early_pregnancy_test_result_weak_positive:
                    HCGResult = 2;
                    RecordSelectEarlyPregnancyButton recordSelectEarlyPregnancyButton2 = (RecordSelectEarlyPregnancyButton) v;
                    recordSelectEarlyPregnancyButton2.clickAction(earlypregnancyView);
                    break;
                case R.id.record_early_pregnancy_test_result_positive:
                    HCGResult = 3;
                    RecordSelectEarlyPregnancyButton recordSelectEarlyPregnancyButton3 = (RecordSelectEarlyPregnancyButton) v;
                    recordSelectEarlyPregnancyButton3.clickAction(earlypregnancyView);
                    break;
                case R.id.record_early_pregnancy_test_result_strong_positive:
                    HCGResult = 4;
                    RecordSelectEarlyPregnancyButton recordSelectEarlyPregnancyButton4 = (RecordSelectEarlyPregnancyButton) v;
                    recordSelectEarlyPregnancyButton4.clickAction(earlypregnancyView);
                    break;
                case R.id.record_early_pregnancy_add_photo_btn:
                    takeHCGPaperPhoto();
                    break;
                case R.id.record_early_pregnancy_question_icon:
                    Intent helpCenterIntent = new Intent(getActivity(), TestPaperHelpActivity.class);
                    helpCenterIntent.putExtra("testPaperType", "HCG");
                    startActivity(helpCenterIntent);
                default:
                    break;
            }
        }
    };

    public View.OnClickListener bUltraClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.record_b_ultra_btn_yes:
                    recordBultraYesBtn.clickAction(bUltraView);
                    record_b_ultra_edit_layout.setVisibility(View.VISIBLE);
                    return;
                case R.id.record_b_ultra_btn_no:
                    recordBultraNoBtn.clickAction(bUltraView);
                    record_b_ultra_edit_layout.setVisibility(View.GONE);
                    return;
                case R.id.record_b_ultra_btn_photo_add:
                    takePhoto();
                    return;
                case R.id.record_b_ultra_photo_trash:
                    if (isToday) {//判断时间是否被改变
                        BUList = dbManager.getRecordBU(date.substring(0, 10), "BUID");
                    } else {
                        BUList = dbManager.getRecordBU(beChangedDate, "BUID");
                    }

                    for (int i = 0; i < BUList.size(); i++) {
                        dbManager.updateRecordBU(BUList.get(i).getBUID(), 1, 1);
                    }
                    recordBuDel.setVisibility(View.GONE);
                    recordBultraPhoto.setImageBitmap(null);
                    testPaperIsChanged = true;
                    return;
                default:
                    return;
            }

        }
    };

    private void StatusBarColor(String dateRecord) {
        long dateCurrent = DateUtil.getStringToDate(dateRecord + " 12:00:00");
        int i = -1;
        for (int n = 0; n < App.dayUnitDSOutputsList.size(); n++) {
            if (dateCurrent == App.dayUnitDSOutputsList.get(n).date) {
                i = n;
                break;
            }
        }
        topBar.setBackgroundResource(getBGcolor(i));
        StatusBarUtil.setColor(getActivity(), getResources().getColor(getBGcolor(i)), 0);
    }

    private int getBGcolor(int i) {
        switch (Locale.getDefault().getLanguage()) {
            case "zh":
                if (i >= 0) {
                    switch (getState(i) + "") {
                        case Constant.kMenstruation:
                            if (App.dayUnitDSOutputsList.get(i).isConfrimOrForecast(App.status) == DayUnitDSOutput.PERIOD_CONFIRM_YJQ) {
                                return R.color.circle_bg_pink;
                            }
                            return R.color.circle_bg_pink_pre;
                        case Constant.kFollicular_phase:
                            return R.color.circle_bg_blue;
                        case Constant.kLuteal:
                            return R.color.circle_bg_yellow;
                        case Constant.kSafe:
                            return R.color.circle_bg_blue;
                        case Constant.kDangerous:
                            return R.color.circle_bg_red;
                        default:
                            return R.color.circle_bg_green;
                    }
                } else {
                    return R.color.lpq_color;
                }
            default:
                if (i >= 0) {
                    switch (getState(i) + "") {
                        case EnConstant.kMenstruation:
                            if (App.dayUnitDSOutputsList.get(i).isConfrimOrForecast(App.status) == DayUnitDSOutput.PERIOD_CONFIRM_YJQ) {
                                return R.color.circle_bg_pink;
                            }
                            return R.color.circle_bg_pink_pre;

                        case EnConstant.kFollicular_phase:
                            return R.color.circle_bg_blue;
                        case EnConstant.kLuteal:
                            return R.color.circle_bg_yellow;
                        case EnConstant.kSafe:
                            return R.color.circle_bg_blue;
                        case EnConstant.kDangerous:
                            return R.color.circle_bg_red;
                        default:
                            return R.color.circle_bg_green;
                    }
                } else {
                    return R.color.lpq_color;
                }
        }

    }


    private String getState(int i) {
        switch (App.dayUnitDSOutputsList.get(i).getPeriod(App.status) + "") {
            case "yjq":
                return getString(R.string.menstruation);
            case "lpq":
                return getString(R.string.follicular_phase);
            case "htq":
                return getString(R.string.luteal);
            case "jhaqq":
                return getString(R.string.safe);
            case "wxq":
                return getString(R.string.dangerous);
            case "jqaqq":
                return getString(R.string.safe);
            case "aqq":
                return getString(R.string.safe);
            default:
                if (App.dayUnitDSOutputsList.get(i).homePageOvulation > 0) {
                    return getString(R.string.ovulation);
                } else if (App.dayUnitDSOutputsList.get(i).homePageOvulation == 0) {
                    return getString(R.string.ovulation_day);
                } else {
                    return getString(R.string.after_ovulation);
                }
        }

    }

    /**
     * B超拍照
     */
    public void takePhoto() {
        boolean hadCameraPermission = SelfPermissionUtil.checkCameraPermission(getContext());
        if (hadCameraPermission) { //有这个权限，做相应处理
            picBUNameID = UUID.randomUUID().toString();
            String mFilePath = getActivity().getExternalFilesDir(null).getAbsolutePath() + "/";// 获取SD卡路径
            mFilePath = mFilePath + picBUNameID + ".jpg";// 文件名
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            Uri uri = Uri.fromFile(new File(mFilePath));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);// 指定存储路径，这样就可以保存原图了
            startActivityForResult(intent, 2);
        } else { //没有权限
            Toast.makeText(getContext(), R.string.photo_permission, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 拍照前，先判断是否有开启相机的权限，若没有则提示用户开启
     */
    private void takePaperPhoto() {
        boolean hadCameraPermission = SelfPermissionUtil.checkCameraPermission(getContext());
        if (hadCameraPermission) { //有这个权限，做相应处理
            if (topBar.getText().equals(dateUtil.getDateTopBar())) {
                isToday = true;
            } else {
                isToday = false;
            }
            if (isToday) {//判断时间是否被改变
                Intent paperPhotoIntent = new Intent(getActivity(), CameraActivity.class);
                paperPhotoIntent.putExtra("result", LHResult);
                paperPhotoIntent.putExtra("date", dateUtil.getDate());
                startActivityForResult(paperPhotoIntent, 1);
            } else {
                Intent paperPhotoIntent = new Intent(getActivity(), CameraActivity.class);
                paperPhotoIntent.putExtra("result", LHResult);
                paperPhotoIntent.putExtra("date", beChangedDate + " 12:00:00");
                startActivityForResult(paperPhotoIntent, 1);
            }

        } else { //没有权限
            Toast.makeText(getContext(), R.string.photo_permission, Toast.LENGTH_SHORT).show();
        }
    }


    private void takeHCGPaperPhoto() {
        boolean hadCameraPermission = SelfPermissionUtil.checkCameraPermission(getContext());
        if (hadCameraPermission) { //有这个权限，做相应处理
            if (topBar.getText().equals(dateUtil.getDateTopBar())) {
                isToday = true;
            } else {
                isToday = false;
            }
            if (isToday) {//判断时间是否被改变
                Intent paperPhotoIntent = new Intent(getActivity(), HCGCameraActivity.class);
                paperPhotoIntent.putExtra("result", HCGResult);
                paperPhotoIntent.putExtra("date", dateUtil.getDate());
                startActivityForResult(paperPhotoIntent, 1);
            } else {
                Intent paperPhotoIntent = new Intent(getActivity(), HCGCameraActivity.class);
                paperPhotoIntent.putExtra("result", LHResult);
                paperPhotoIntent.putExtra("date", beChangedDate + " 12:00:00");
                startActivityForResult(paperPhotoIntent, 1);
            }

        } else { //没有权限
            Toast.makeText(getContext(), R.string.photo_permission, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        AppLog.e("resultCode  " + resultCode);
        testPaperIsChanged = true;
        switch (resultCode) {
            case 1:
                LHList = dbManager.getRecordLH(date.substring(0, 10), "LHPaperID");
                RecordInfo lhInfo = new RecordInfo();
                if (LHList.size() <= 8) {
                    lhInfo.setLHDate(data.getStringExtra("picNameDate"));
                    lhInfo.setLHPaperID(data.getStringExtra("picNameID"));
                    lhInfo.setLHIsSynced(0);
                    LHItems.add(lhInfo);
                    ovuPaperPhotoAdapter.notifyDataSetChanged();
                    fixListViewHeight(recordOvuPhotoList);
                    Toast.makeText(getContext(), R.string.pic_save_to + getActivity().getExternalFilesDir(null).getAbsolutePath() + R.string.finder, Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
                Glide.with(getContext()).load("file://" + getActivity().getExternalFilesDir(null).getAbsolutePath() + "/" + "photo" + ".jpg").into(recordBultraPhoto);
                break;
            case 3:
                Toast.makeText(getContext(), R.string.eight_lh, Toast.LENGTH_SHORT).show();
                break;
            case 4:
                Toast.makeText(getContext(), R.string.one_hcg, Toast.LENGTH_SHORT).show();
                break;
            case 5:
                HCGItems.clear();
                RecordInfo hcgInfo = new RecordInfo();
                hcgInfo.setHCGDate(data.getStringExtra("picNameDate"));
                hcgInfo.setHCGPaperID(data.getStringExtra("picNameID"));
                hcgInfo.setHCGIsSynced(0);
                HCGItems.add(hcgInfo);
                earlyPregnancyPaperPhotoAdapter.notifyDataSetChanged();
                fixHCGListViewHeight(recordEarlyPregnancyList);
                Toast.makeText(getContext(), R.string.pic_save_to + getActivity().getExternalFilesDir(null).getAbsolutePath() + this.getString(R.string.finder), Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }

        switch (requestCode) {
            case 2://显示B超拍照图片

                if (isToday) {//判断时间是否被改变
                    dbManager.insertRecordBU(App.userName, date, picBUNameID, 0, 0);
                } else {
                    dbManager.insertRecordBU(App.userName, beChangedDate + " 12:00:00", picBUNameID, 0, 0);
                }
                String s = getActivity().getExternalFilesDir(null).getAbsolutePath() + "/" + picBUNameID + ".jpg";
                File tempFile = new File(s);
                BUBitmap = getBitmapFromUri(Uri.fromFile(tempFile));
                if (BUBitmap != null) {
                    Glide.with(getContext()).load("file://" + getActivity().getExternalFilesDir(null).getAbsolutePath() + "/" + picBUNameID + ".jpg").into(recordBultraPhoto);
                    recordBuDel.setVisibility(View.VISIBLE);
                    Toast.makeText(getContext(), R.string.pic_save_to + getActivity().getExternalFilesDir(null).getAbsolutePath() + this.getString(R.string.finder), Toast.LENGTH_SHORT).show();
                }
                break;
        }

    }


    /**
     * uri转bitmap
     *
     * @param uri
     * @return
     */
    private Bitmap getBitmapFromUri(Uri uri) {
        try {
            // 读取uri所在的图片
            BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
            bitmapOptions.inSampleSize = 4;
            Bitmap bitmap = BitmapFactory.decodeStream(getContext().getContentResolver().openInputStream(uri), null, bitmapOptions);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public void scrollToBottom(final View scroll, final int layoutId) {
        Handler mHandler = new Handler();

        mHandler.post(new Runnable() {
            public void run() {
                if (scroll == null) {
                    return;
                }
                int offset = 0;
                for (int i = 0; i < RecordFragmentCommonList.recordInnerLayout.length; i++) {
                    if (layoutId == RecordFragmentCommonList.recordInnerLayout[i]) break;
                    View viewInner = viewFragment.findViewById(RecordFragmentCommonList.recordInnerLayout[i]);
                    offset += viewInner.getMeasuredHeight();
                }
                if (offset < 0) {
                    offset = 0;
                }
                scroll.scrollTo(0, offset);
            }
        });
    }

    public void fixListViewHeight(ListView listView) {

        int totalHeight = 0;
        if (ovuPaperPhotoAdapter == null) {
            return;
        }
        for (int index = 0, len = ovuPaperPhotoAdapter.getCount(); index < len; index++) {
            View listViewItem = ovuPaperPhotoAdapter.getView(index, null, listView);
            // 计算子项View 的宽高
            listViewItem.measure(0, 0);
            // 计算所有子项的高度和
            totalHeight += listViewItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // listView.getDividerHeight()获取子项间分隔符的高度
        // params.height设置ListView完全显示需要的高度
        params.height = totalHeight + (listView.getDividerHeight() * (ovuPaperPhotoAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public void fixHCGListViewHeight(ListView listView) {

        int totalHeight = 0;
        if (earlyPregnancyPaperPhotoAdapter == null) {
            return;
        }
        for (int index = 0, len = earlyPregnancyPaperPhotoAdapter.getCount(); index < len; index++) {
            View listViewItem = earlyPregnancyPaperPhotoAdapter.getView(index, null, listView);
            // 计算子项View 的宽高
            listViewItem.measure(0, 0);
            // 计算所有子项的高度和
            totalHeight += listViewItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // listView.getDividerHeight()获取子项间分隔符的高度
        // params.height设置ListView完全显示需要的高度
        params.height = totalHeight + (listView.getDividerHeight() * (earlyPregnancyPaperPhotoAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    private void showTemperatureDialog(String currentTemper, final int position) {
        TemperaturePickerDialog dialog;
        if (getResources().getString(R.string.record_bbt_temperature).equals(currentTemper) || "".equals(currentTemper))
            dialog = new TemperaturePickerDialog(getActivity(), "36.50");
        else {
            String value = currentTemper.substring(0, currentTemper.indexOf("℃")).trim();
            String value5bits;
            if (value.length() == 4) {
                value5bits = value + "0";
            } else {
                value5bits = value;
            }
            dialog = new TemperaturePickerDialog(getActivity(), value5bits);
        }
        dialog.setOnTemperatureeSetListener(new TemperaturePickerDialog.OnTemperatureSetListener() {
            @Override
            public void OnTemperatureSet(AlertDialog dialog, String temperature) {
                if (position == 1) {
                    recordTemperatureRecordBtn.setText(temperature);
                    recordTemperatureRecordBtn.clickAction(viewFragment);
                    recordTemperatureTimeBtn.setText(DateUtil.getCurrentTime());
                } else if (position == 2) {
                    bbtText.setText(temperature);
                    selectedDayTemper.get(0).setTemperature(Double.valueOf(temperature.substring(0, temperature.indexOf("℃"))));
                } else if (position == 3) {
                    otherTemperature1Text.setText(temperature);
                    selectedDayTemper.get(1).setTemperature(Double.valueOf(temperature.substring(0, temperature.indexOf("℃"))));
                } else if (position == 4) {
                    otherTemperature2Text.setText(temperature);
                    selectedDayTemper.get(2).setTemperature(Double.valueOf(temperature.substring(0, temperature.indexOf("℃"))));
                } else if (position == 5) {
                    otherTemperature3Text.setText(temperature);
                    selectedDayTemper.get(3).setTemperature(Double.valueOf(temperature.substring(0, temperature.indexOf("℃"))));
                }

            }
        });
        dialog.show();
        dialog.setCancelable(false);
        toggleSoftInput();
    }

    private void showTimeDialog(String currentTime, final int position) {
        DateTimePickerDialog dialog;
        if (getResources().getString(R.string.record_bbt_time).equals(currentTime) || getResources().getString(R.string.record_copulation_time).equals(currentTime) || getResources().getString(R.string.record_ovulation_time).equals(currentTime))
            dialog = new DateTimePickerDialog(getActivity(),
                    System.currentTimeMillis());
        else {
            int hour = Integer.parseInt(currentTime.substring(0, currentTime.indexOf(":")));
            int minute = Integer.parseInt(currentTime.substring(currentTime.indexOf(":") + 1));
            Calendar mDate = Calendar.getInstance();
            mDate.setTimeInMillis(System.currentTimeMillis());
            mDate.set(Calendar.HOUR_OF_DAY, hour);
            mDate.set(Calendar.MINUTE, minute);
            mDate.set(Calendar.SECOND, 0);
            dialog = new DateTimePickerDialog(getActivity(),
                    mDate.getTimeInMillis());
        }
        dialog.setOnDateTimeSetListener(new DateTimePickerDialog.OnDateTimeSetListener() {
            public void OnDateTimeSet(AlertDialog dialog, String time) {
                if (position == 1) {
                    recordTemperatureTimeBtn.setText(time);
                    recordTemperatureTimeBtn.clickAction(bbtView);
                } else if (position == 2) {
                    recordCopulationTimeBtn.setText(time);
                    recordCopulationTimeBtn.clickAction(copulationView);
                    if (copulationHaveSex == 0) {
                        recordCopulationYesBtn.clickAction(copulationView);
                        copulationTick.setImageResource(R.drawable.record_tick_white);
                        copulationCross.setImageResource(R.drawable.record_copulation_cross);
                    }

                } else if (position == 3) recordOvulationTimeBtn.setText(time);

            }
        });
        dialog.setCancelable(false);
        dialog.show();
        toggleSoftInput();
    }

    private void showBrandDialog() {

        BrandPickerDialog brandPickerDialog;
        brandPickerDialog = new BrandPickerDialog(getActivity());
        brandPickerDialog.setOnBrandSetListener(new BrandPickerDialog.OnBrandSetListener() {
            @Override
            public void OnBrandSet(AlertDialog dialog, String brand) {
                recordOvulationPaperBrandBtn.setText(brand);
            }
        });
        brandPickerDialog.setCancelable(false);
        brandPickerDialog.show();
        toggleSoftInput();
    }

    private void toggleSoftInput() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Subcriber
    private void setViewPagerNum(ViewPagerNumMsg viewPagerNumMsg) {
        AppLog.i("viewPagerNumMsg:" + viewPagerNumMsg.toString());
        int num = viewPagerNumMsg.getRespCode();
        if (null != verticalViewPager)
            verticalViewPager.setCurrentItem(num);
    }

    /**
     * 接收HomeFragment传来的日期，用于更改RecordFragment对应日期下的记录数据
     *
     * @param date
     */
    private void setRecordDateToChangeRecordMsg(String date) throws ParseException {
        initTestPaperMsg(dateUtil.getSimpleDateAddOrMinus(date));
    }

    /**
     * 初始化所以试纸
     *
     * @param date
     */
    private void initTestPaperMsg(String date) {
        initLHPaperMsg(date);
        initHCGPaperMsg(date);
        initBUPaperMsg(date);
    }

    private void initLHPaperMsg(String date) {
        LHItems.clear();
        LHList = dbManager.getRecordLH(date, "LHPaperID");
        for (int i = 0; i < LHList.size(); i++) {
            RecordInfo lhInfo = new RecordInfo();
            if (LHList.get(i).getLHIsDelete() == 0) {
                lhInfo.setLHDate(LHList.get(i).getLHDate());
                lhInfo.setLHPaperID(LHList.get(i).getLHPaperID());
                lhInfo.setLHIsSynced(LHList.get(i).getLHIsSynced());
                LHItems.add(lhInfo);
            }
        }
        ovuPaperPhotoAdapter = new OvuPaperPhotoAdapter(getContext(), LHItems);
        recordOvuPhotoList.setAdapter(ovuPaperPhotoAdapter);
        fixListViewHeight(recordOvuPhotoList);
    }

    private void initHCGPaperMsg(String date) {
        //初始化试纸图片
        HCGItems.clear();
        HCGList = dbManager.getRecordHCG(date, "HCGPaperID");
        for (int i = 0; i < HCGList.size(); i++) {
            RecordInfo hcgInfo = new RecordInfo();
            if (HCGList.get(i).getHCGIsDelete() == 0 && HCGList.get(i).getHCGIsSynced() == 1) {
                hcgInfo.setHCGDate(HCGList.get(i).getHCGDate());
                hcgInfo.setHCGPaperID(HCGList.get(i).getHCGPaperID());
                hcgInfo.setHCGIsSynced(HCGList.get(i).getHCGIsSynced());
                HCGItems.add(hcgInfo);
            }
        }
        earlyPregnancyPaperPhotoAdapter = new EarlyPregnancyPaperPhotoAdapter(getActivity(), HCGItems);
        recordEarlyPregnancyList.setAdapter(earlyPregnancyPaperPhotoAdapter);
        fixHCGListViewHeight(recordEarlyPregnancyList);
    }

    private void initBUPaperMsg(String date) {
        //初始化试纸图片
        recordBuDel.setVisibility(View.GONE);
        recordBultraPhoto.setImageBitmap(null);

        BUList = dbManager.getRecordBU(date, "BUID");
        for (int i = 0; i < BUList.size(); i++) {
            if (BUList.size() != 0 && BUList.get(i).getBUIsDelete() == 0 && BUList.get(i).getBUIsSynced() == 1) {
                String picURL = App.gynaeUrlPath + "bultrasonog/" + App.userName + "/" + BUList.get(i).getBUDate().substring(0, 10) + "/" + BUList.get(i).getBUID() + ".jpg";
                Glide.with(getContext()).load(picURL).into(recordBultraPhoto);
                recordBuDel.setVisibility(View.VISIBLE);
            }
        }
    }

    @Subcriber
    private void dealTemperUploadMsg(TemperUploadMsg temperUploadMsg) {
        AppLog.i("temperUploadMsg : " + temperUploadMsg.toString());
        int updateCode = temperUploadMsg.getUpdateCode();
        switch (updateCode) {

            case 1:
                selectedDayTemper = dbManager.getSelectedDayTemperature(App.userName, dateRecord);
                sortSelectedTemper();
                updateTemperatureShowView();
                UserRecordData updatedRecord = dbManager.getSelectedDayRecordData(App.userName, dateRecord);
                userRecordData.setId(updatedRecord.getId());
                break;
            case 2:
                if (progressDialog != null && progressDialog.isShowing()) {
                    //loadWebview();
                    EventBus.getDefault().post(new CurveMsg());
                    StatusBarColor(dateRecord);
                    progressDialog.setMessage(getString(R.string.save_success));
                    (new Handler()).postDelayed(new Runnable() {
                        @Override
                        public synchronized void run() {
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                                progressDialog = null;
                            }
                            deleteDayTemper.clear();
                            //Toast.makeText(getActivity(), R.string.save_success, Toast.LENGTH_SHORT).show();
                            initValue();

                            if(isMensesAlgorithmUsed)
                                jumpToCalendarActivity();
                        }
                    }, 1000);

                    //optimizedFragmentTabHost.setCurrentTab(1);
                }
                break;
            case 5:
                AppLog.i("uploadCycleDatas start ");
                uploadCycleDatas();
                break;

            case App.HTTP_RESP_TOKEN_TIME_OUT:
                AppLog.e("App.HTTP_RESP_TOKEN_TIME_OUT");
                uploadRecordInfo();
                break;

            default:
                break;
        }
    }

    private void jumpToCalendarActivity(){
        (new Handler()).postDelayed(new Runnable() {
            @Override
            public synchronized void run() {
                isMensesAlgorithmUsed = false;
                Intent intent = new Intent();
                intent.putExtra("dateRecord",dateRecord);
                intent.setClass(getActivity(), CalendarActivity.class);
                startActivity(intent);
            }
        }, 500);
    }

    private void uploadCycleDatas() {

        OKHttpUtil okHttpClient = new OKHttpUtil(RecordFragment.this.getActivity());
        String appendUrl = "cycle/replaceCycle.json";
        try {
            AppLog.i("cycleData = " + jsonArrayCycleDatas);
            AppLog.i("userData = " + jsonArrayUserDatas);
            AppLog.i("userInfo = " + jsonObjectUserData);
            okHttpClient.add("authToken", App.authToken);
            AppLog.i("authToken = " + App.authToken);
            if (null != jsonArrayCycleDatas)
                okHttpClient.add("cycleData", jsonArrayCycleDatas);
            if (null != jsonArrayUserDatas)
                okHttpClient.add("userData", jsonArrayUserDatas);
            if (null != jsonObjectUserData)
                okHttpClient.add("userInfo", jsonObjectUserData);
            if (null == jsonArrayCycleDatas && null == jsonObjectUserData && null == jsonArrayUserDatas)
                return;
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    algorithm.saveALData2Sqlite(0);
                    TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                    temperUploadMsg.setUpdateCode(2);
                    EventBus.getDefault().post(temperUploadMsg);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                    try {
                        String str = response.body().string();
                        AppLog.i("cycle/replaceCycle response:" + str);
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (200 == respCode) {
                            AppLog.i("UploadCycleData onResponse success!");
                            temperUploadMsg.setUpdateCode(2);
                            EventBus.getDefault().post(temperUploadMsg);
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            uploadCycleDatas();
                        } else {
                            algorithm.saveALData2Sqlite(0);
                            temperUploadMsg.setUpdateCode(2);
                            AppLog.i("UploadCycleData onResponse failed! respCode = " + respCode);
                            EventBus.getDefault().post(temperUploadMsg);
                        }
                    } catch (JSONException e) {
                        algorithm.saveALData2Sqlite(0);
                        e.printStackTrace();
                        temperUploadMsg.setUpdateCode(2);
                        EventBus.getDefault().post(temperUploadMsg);
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("UploadCycleData JSONException!");
            algorithm.saveALData2Sqlite(0);
            e.printStackTrace();
            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
            temperUploadMsg.setUpdateCode(2);
            EventBus.getDefault().post(temperUploadMsg);

        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {

            topBar.setText(App.getPreference(Constant.kStatusDay));
            try {
                setRecordDateToChangeRecordMsg(App.getPreference(Constant.kStatusDay).toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            dateRecord = App.getPreference(Constant.kStatusDay).split(" ")[0];
            AppLog.i("RecordFragment date = " + date);
            StatusBarColor(dateRecord);
            initValue();
        }
    }

}
